< Previous | Contents | Next >
Global Search-And-Replace
vi uses an ex command to perform search-and-replace operations (called “substitution” in vi) over a range of lines or the entire file. To change the word “Line” to “line” for the entire file, we would enter the following command:
:%s/Line/line/g
:%s/Line/line/g
Let's break this command down into separate items and see what each one does:
Table 12- 5:An example of global search-and-replace syntax
Item Meaning
Item Meaning
: The colon character starts an ex command.
![]()
% Specifies the range of lines for the operation. % is a shortcut meaning from the first line to the last line. Alternately, the range could have been specified 1,5 (since our file is five lines long), or 1,$ which means “from line 1 to the last line in the file.” If the range of lines is omitted, the operation is only performed on the current line.
![]()
Search-And-Replace
![]()
s Specifies the operation. In this case, substitution (search-and- replace).
![]()
/Line/line/ The search pattern and the replacement text.
![]()
g This means “global” in the sense that the search-and-replace is performed on every instance of the search string in the line. If omitted, only the first instance of the search string on each line is replaced.
![]()
After executing our search-and-replace command our file looks like this:
The quick brown fox jumped over the lazy dog. It was cool. line 2
line 3
line 4
line 5
The quick brown fox jumped over the lazy dog. It was cool. line 2
line 3
line 4
line 5
We can also specify a substitution command with user confirmation. This is done by adding a “c” to the end of the command. For example:
:%s/line/Line/gc
:%s/line/Line/gc
This command will change our file back to its previous form; however, before each sub- stitution, vi stops and asks us to confirm the substitution with this message:
replace with Line (y/n/a/q/l/^E/^Y)?
replace with Line (y/n/a/q/l/^E/^Y)?
Each of the characters within the parentheses is a possible choice as follows:
Table 12-6: Replace Confirmation Keys
Key Action
Key Action
y Perform the substitution.
![]()
n Skip this instance of the pattern.
![]()
a Perform the substitution on this and all subsequent instances of the pattern.
![]()
![]()
q or Esc Quit substituting.
![]()
l Perform this substitution and then quit. Short for “last.”
![]()
Ctrl-e, Ctrl-y Scroll down and scroll up, respectively. Useful for viewing the context of the proposed substitution.
![]()
If you type y, the substitution will be performed, n will cause vi to skip this instance and move on to the next one.
Documentation