//View Tip #840
Similar Tips
» Sudo from vim to write file
» Making shell scripts executable via editor hooks
» Quickly empty a file in vi


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
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 »


Add your comment

Comments are currently disabled
Couldn't you do this with ex instead of full blown Vim?
Posted 2009-06-18 13:46:55
Sed is more designed for this:

sed -i "5,10s/a/b/g" filename

Does exactly what you are suggesting without invoking all of vim.
Posted 2009-06-18 13:59:18
I've used:
perl -p -i -e "s/old/new" <FILENAME>

It has served me very well... and you can use perl regex if you are so inclined.
Posted 2009-06-18 14:08:54
Yes, you could do this all the ways mentioned in the above comments, but this is just an alternative.


Also, although there are better tools for this particular task, this could be used with other vim commands.

I guess the purpose of the tip is more to bring attention to the fact you can run a vim command directly than to do a substitution which I'm sure we all have over 9000 ways of doing already!
Posted 2009-06-18 14:29:05

Home Latest Browse Top 25 Random Hall Of Fame Contact Submit