Sometimes, halfway through a document or at the end of a draft, you may recognize inconsistencies in the way that you refer to certain things. Or, in a manual, some product whose name appears throughout your file is suddenly renamed (marketing!). Often enough it happens that you have to go back and change what you've already written, and you need to make the changes in several places.
The way to make these changes is with a powerful change command called global replacement. With one command you can automatically replace a word (or a string of characters) wherever it occurs in the file.
In a global replacement, the ex editor checks each line of a file for a given pattern of characters. On all lines where the pattern is found, ex replaces the pattern with a new string of characters. For right now, we'll treat the search pattern as if it were a simple string; later in the chapter we'll look at the powerful pattern-matching language known as regular expressions .
The substitute command has the syntax:
This changes the first occurrence of the pattern old to new on the current line. The / (slash) is the delimiter between the various parts of the command. (The slash is optional when it is the last character on the line.)
A substitute command with the syntax:
occurrence of old
current line, not just the first occurrence.
By prefixing the
This command will change every occurrence of old to new within the entire file:
Global replacement is much faster than finding each instance of a string and replacing it individually. Because the command can be used to make many different kinds of changes, and because it is so powerful, we will first illustrate simple replacements and then build up to complex, context-sensitive replacements.
It makes sense to be overly careful when using a search and replace command.
It sometimes happens that what you get is not what you expect.
You can undo any search and replacement command by
It's wise to be cautious and know exactly what is going to be
changed in your file.
If you'd like to see what the search turns up
and confirm each replacement before it is made,
It will display the entire line where the string has been located, and the string will be marked by a series of carets (^^^^):
copyists at his school ^^^_
If you want to make the replacement, you must enter
this can be used for invitations, signs, and menus. ^^^_
The combination of the vi