Global replacement in Vim

This article comes from    http://blog.csdn.net/shuangde800



This article is a note taken while learning "Using the vi editor, edited by Lamb & Robbins".

Contents of this article:
Basic global replacement
confirm replacement
context sensitive substitution

This article agrees:
$  +  command  means in the normal bash command line
:   +  command  means in the ex (command) mode of vim, press " Ctrl " + " : " to enter

------------------------------------------------------------------------------------------------



Basic syntax of the substitution command


In global replacement, the ex editor checks each line in the file using the specified character pattern. Where the pattern is found on all lines, ex replaces the pattern with the new string.

What global substitution really uses is the two ex commands  : g (global) and :s (switch substitution).

The syntax of the substitution command is as follows:
:s / old / new /  
This will modify the first occurrence of the current mode old to new. / (slash) is the separator between different parts of the command (when the slash is the last character of the line, it can be omitted)

Substitute commands of the form:
:s / old / new / g
把当前行old的每次出现改为new,而不只是该行的第一个old。:s命令允许替换串后面带有选项,上面语法中的g代表全局(g选项影响一行中的每个模式,不要把它与影响文件中所有行的:g命令混淆)

通过在:s命令前加上地址前缀,可以把它的范围扩展到多行。例如下面命令把50行到100行的old的每次出现都改为new:
:50, 100 s / old / new / g

下面的命令把整个文件中的old的每次出现都改为new:
:1, $s / old / new / g
我们知道%等价于1,$,所以上行命令也可以这样写:
:% s / old / new / g




确认替换


使用搜索替换命令有时候会出错,而得到不想要的结果。所以小心并确认文件中需要修改的内容是一个明智的做法

在替换命令尾部加上c (confirm用于确认),在替换每个old前都会提示并确认:
:1, 30 s /old/new/ gc
将会出现提示replace with hehe (y/n/a/q/l/^E/^Y)?  
y替换,n不替换,a替换所有,q放弃,l替换第一个并进入插入模式,^E和^Y是提示你用Ctrl+e或Ctrl+y来滚动屏幕的。

 


上下文相关替换


除了直接使用一个单词(或短语)替换另一个,还有稍微复杂的全局替换语法。这些语法可以对一个模式进行搜索,一旦找到含有模式的行,就可以使用不同与模式的串进行替换,我们把这种替换叫做上下文相关替换

语法格式如下:
:g /pattern/s/old/new/g     将会把包含pattern的行中,把所有old替换为new
第一个g表示是在文件的所有行上执行的命令,模式pattern识别要发生替换的行。在那些包含模式pattern的行上,ex将把old替换(s)为new。最后的g表示在该行上进行全部替换。

如果用来进行搜索的模式与想要修改的模式相同,那么就不必重复它:
:g/string/s//new/g  等价于  :g/string/s/string/new/g
还要注意:
:g/string/s//new/g  也等价于 :% s/string/new/g
可以用第二种方式少输一些字符

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326028859&siteId=291194637