Context-Sensitive Replacement

The simplest global replacements substitute one word (or a phrase) for another. If you have typed a file with several misspellings (editer for editor), you can do the global replacement:

:%s/editer/editor/g

This substitutes editor for every occurrence of editer throughout the file.

There is a second, slightly more complex syntax for global replacement. This syntax lets you search for a pattern, and then, once you find the line with the pattern, make a substitution on a string different from the pattern. You can think of this as context-sensitive replacement.

The syntax is as follows:

:g/pattern/s/old/new/g

The first g tells the command to operate on all lines of a file. pattern identifies the lines on which a substitution is to take place. On those lines containing pattern, ex is to substitute (s) for old the characters in new. The last g indicates that the substitution is to occur globally on that line.

For example, as we write this book, the XML directives <keycap> and </keycap> place a box around ESC to show the Escape key. You want ESC to be all in caps, but you don’t want to change any instances of Escape that might be in the text. To change instances of Esc to ESC only when Esc is on a line that contains the <keycap> directive, you could enter:

:g/<keycap>/s/Esc/ESC/g

If the pattern being used to find the line is the same as the one you want to change, you don’t have to repeat it. The command:

:g/string/s//new/g

would search for lines containing string ...

Get Learning the vi and Vim Editors, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.