Technical Leader

Vim Substitute Command

The following command is the substitute command, you can learn more about this command by reading :help substitute (or if you prefer the shorthand version :he su). If you did the preceding you will notice that the help shows the substitute command as :[range]s[ubstitute]/{pattern}/{string}/ (the help also shows all of the possible flags, which I omitted here on purpose). Just in case you didn't know, since range is enclosed in square brackets that means it is optional. Also you will notice that the :s can also be spelled out as :substitute, I am sure that most people will prefer the :s syntax.

To replace the first occurrence of aspirin with foo in the current line:

:s/aspirin/foo

To replace the first occurrence of aspirin with foo in every line:

:%s/aspirin/foo

You will notice the only difference in the two preceding lines is the % sign. The % sign specifies a range, basically saying every line in the file, but the help (:he range) says that it is equal to 1,$. You are probably confused with the dollar sign also which you probably think of as the last character on the line but $ is range command meaning last line in file. I will not continue more with ranges (to read more about ranges, see my range tutorial), I just wanted to show what all is possible and where to look.

You will notice that both of the operations above will only work once for each line. So if you have aspirin in a line more than once, then only the first instance will be changed.

In order to change every occurrence of aspirin to foo:

:%s/aspirin/foo/g

One problem that many users face is editing DOS/Windows files on Linux, when viewed with Vim you will see ^M at the end of the lines. One way to fix this problem is the following:

:%s/r//g

The r is the extra character that Windows adds for the end of line marker, there is an empty string to replace it with as noted with //

Some of the special characters can easily be handled by escaping them, just use a preceding in these cases. There are a few others which need an extra step, such is the case for the ? character. In order to replace this character with a string (such as foo) then one would use the following command:

:s/v?/foo/