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   ZhangZhihuiAAA  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示