//Tips tagged vim

Latest tips by RSS
Click here to subscribe

Follow Shell-Fu on Twitter
Click here to follow

Follow Shell-Fu on identi.ca
Click here to follow
I often open a file and start editing only to realize later that I don't have write permissions when I get the old "E212: Can't open file for writing" error.
The vim command below can be user to save the file without the need to save it to a temp file and then copy it back again.
The vim command below can be user to save the file without the need to save it to a temp file and then copy it back again.
:w !sudo tee %
If you spend a lot of time creating new shell scripts then it can be very useful to make them executable by default. To do this in Vim add the following lines to the end of your ~/.vimrc file - creating it if necessary:
This code will automatically change the file to executable if the first line contains both "#!" and "/bin/".
Once you add #!/bin/sh (for example) to the start of a file and save it, the file will be immediately executable.
" " automatically give executable permissions if file begins with #! and contains " '/bin/' in the path " au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod a+x <afile> | endif | endif
This code will automatically change the file to executable if the first line contains both "#!" and "/bin/".
Once you add #!/bin/sh (for example) to the start of a file and save it, the file will be immediately executable.
We can use vim to make changes to a file all in one command, for example
This will open the file 'filename' and replace all occurances of 'a' with 'b' on lines 5-10. The file will then be written and closed. To edit the file after the change, just remove the ' | wq' from the end of the command.
vim -c "5,10s/a/b/g | wq" filename
This will open the file 'filename' and replace all occurances of 'a' with 'b' on lines 5-10. The file will then be written and closed. To edit the file after the change, just remove the ' | wq' from the end of the command.
A few quick ways to empty a file of text in vi (all of these are done in command mode):
:1,$d -- :1[enter]dG -- ggdG