//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
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:

"
" 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.


View Comments »



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.

:w !sudo tee %


View Comments »

We can use vim to make changes to a file all in one command, for example

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.


View Comments »

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


View Comments »




Home Latest Browse Top 25 Random Hall Of Fame Contact Submit