Tuesday, August 27, 2013

How to edit multiple files automatically with vim

From time to time I may have a slew of files that I need to make bulk changes to but don't want to edit each one by hand.  A quick and easy way to do this is by using vim's -c option.  For those of you who are thinking "what about sed?" just hold on to your seat.  The sed command is also a favorite of mine, but the mood just struck me today to talk about vim.

Almost everyone who uses Unix or Linux agrees that vim (or vi for the super-hardcore folks) is the editor of choice.  Pico and nano are for sissies.  Emacs, you say?  I believe the old joke goes "Emacs is a great operating system but lacks a good editor."  I give you a +1 if you get the joke.  Kidding aside, let me get to the point of the post.

Vim, or vi improved for the unfamiliar, allows you to edit a file without getting your hands dirty via the -c option.  This option allows you to pass a vim command directly from the *nix command line.  With this nifty trick, it's easy to iterate through a list of files and perform the same edit on all of them in no time flat.  Let's say that you have ten files all containing a host named foo.net which needs to be changed to bar.com.  if all of the files are sitting in one directory and for simplicity's sake, named 1-10.txt you could do something like this:
for file2edit in *.txt; do vim -c "%s/foo.net/bar.com/g" -c "wq" $file2edit; done
The command will loop over all files ending in *.txt and do a simple string substitution followed by a save and quit in vim.  Of course, depending on your situation you will like need to tweak the for loop or vim command line a bit, but this should give you an idea of the potential time savings.  I'll try to post a similar example using sed soon.