vi search replace - how to repeat vi commands across multiple files

Another cool feature of the vi and vim editors is that you can easily re-use some search and replace commands across files. For example, I was just editing several HTML files and needed to do the exact same thing to each file: find a certain line, and then delete that line and the line right after it. Fortunately this is very easy to do in vi.

To edit multiple files in vi I first issue this command from the Linux command prompt:

vi *.html

The vi editor now has all files in the current directory ending with the ".html" extension lined up so I can edit one right after the other. The first file in the list is now shown in the editor.

The next thing I do is search for the pattern where I know I want to start my deleting. The pattern I'm looking for is meta name="description", so I issue the search command like this:

/meta name="description"

The "/" character takes me to last line mode and tells vi to search for whatever I type next. After typing my search pattern I just hit the [Enter] key to initiate the search.

When vi locates the line I then issue the command to delete two lines, like this:

2dd

Cool, the current line and next line are deleted, just like I wanted. Now I save the changes to this file and move on to the next file by issuing this command:

:wn

This means "write this file to disk, and move to the next file".

Now that vi is showing me the next HTML file, I just issue the "next" command (the letter 'n'), and vi repeats the previous search command, taking me to the meta name="description" line in this file. Now, I just issue the "repeat previous command" command (the "." (decimal) character, some times referred to as the "dot command"), and the same delete command I issued in the first file is executed in this file. How cool is that?!

Now the pattern is simple. To move on to the next file I again type the :wn command, then issue the same next ("n") and repeat (".") commands, and keep moving through all the files as fast as I can.

When I try to write the last file using the :wn command vi complains with this message: "Cannot go beyond last file". All this means is that I've reached the end of my list of HTML files to edit -- I'm done. Here I just type :wq (the "q" is for "quit") command and I'm returned to the command line.

I love this part of vi. If I only have a few files to change I'll do things this way. But, if I have a lot of files I need to change like this I'll use the sed command. I'll show you how to do that in a future blog.