ZhangZhihui's Blog  

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. 

 

Below command can alos do global replacement:

:g//s/old/new/g

 

posted on 2023-11-27 16:26  ZhangZhihuiAAA  阅读(31)  评论(0)    收藏  举报