vim substitute example: A global pattern substitution

One of the nice things about the vim editor is the ability to easily fire off one command that changes patterns throughout your entire file. For instance, as I was working on editing my Function Point Analysis tutorial the following HTML string pattern kept re-appearing throughout the entire document, and needed to be replaced:

td align="CENTER"

This character sequence (pattern) was created over and over again by the Latex2html generator that I use for creating long tutorials, and I wanted to substitute all those occurrences with something much simpler, namely this:

td

Fortunately in the vim editor this is pretty easy to do, well, at least if you know the vim substitute command.

For instance, when I was editing one of these files with vi, I'd first hit the [Esc] key to make sure I was in command mode. Then I typed this vim substitute command:

:1,$s/td align="CENTER"/td/g

and hit [Enter] at the end of the command.

The initial ":" character opens up the command line at the bottom of the vim editor. The rest of the command sequence is read as "From the first line of the file to the last line swap every occurrence of the pattern td align="CENTER" with the pattern td, and do this globally on each line (the "g" at the end of the sequence, where 'globally' means 'execute this replacement command as many times per line as needed')". The "first line to last line" part comes from the 1,$, and the "swap" part comes from the s just after the dollar sign.

I use this vi substitute pattern over and over again when editing files with vi/vim. One last note is that you can easily use regular expressions when making these substitutions. I'll show more of these examples in a future post.