VI - Global Replacement

发布时间 2023-11-27 16:30:01作者: ZhangZhihuiAAA

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: :g (global) and :s (substitute). Since the syntax of global replacement commands can get fairly complex, let's look at it in stages.

The substitute command has the syntax:

:s/old/new/

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/old/new/g 

changes every occurrence of old to new on the current line, not just the first occurrence. The :s command allows options following the substitution string. The g option in the syntax above stands for global. (The g option affects each pattern on a line; don't confuse it with the :g command, which affects each line of a file.)

By prefixing the :s command with addresses, you can extend its range to more than one line. For example, this line will change every occurrence of old to new from line 50 to line 100: 

:50,100s/old/new/g

This command will change every occurrence of old to new within the entire file: 

:1,$s/old/new/g

You can also use % instead of 1,$ to specify every line in a file. Thus the last command could also be given like this: 

:%s/old/new/g

Global replacement is much faster than finding each instance of a string and replacing it individually.