6. Global Replacement
Contents:
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 .
Global replacement really uses two
ex
commands: The substitute command has the syntax:
:s/ 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:
:s/
changes
every
occurrence of
old
to
new
on the
current line, not just the first occurrence.
The
By prefixing the
:50,100s/ will change every occurrence of old to new from line 50 to line 100. The following command will change every occurrence of old to new within the entire file:
:1,$s/
You can also use
:%s/ 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 are first going to illustrate simple replacements and then build to complex, context-sensitive replacements. 6.1 Confirming Substitutions
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
entering
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,
add the
:1,30s/his/the/gc 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
commands
|
|