vim提供了:s (substitute)命令进行替换和查找,基本格式如下:
:{作用范围}s{分隔符}{目标}{分隔符}{替换}{分隔符}{替换标志}
作用范围
% :全文
n,m :第n行到第m行
.,$ :当前行到最后一行
.,+n :当前行到其后n行
'<,>' :visual模式下选择区域后输入: 得到选区
分隔符
常用为/ 作为分隔符,可以使用其他字符,但同一命令需要保持一致。
替换标志
[空] :仅从光标开始替换第一次出现的,仅替换一次
g :全局替换,所有出现的都替换
i :忽略大小写
I :不忽略大小写
c :全局替换时进行确认,按下y表示替换,n表示不替换,a表示替换所有,q表示退出查找模式, l表示替换当前位置并退出。^E与^Y是光标移动快捷键
查找
. ,* , ,[ ,^ ,and $ : metacharacters
+ ,? ,| ,& ,{ ,( ,and ) :must be escaped to use their special function
/ is / (use backslash + forward slash to search for forward slash)
t is tab,s is whitespace (space or tab)
n is newline,r is CR (carriage return = Ctrl-M = ^M)
- After an opening
[ ,everything until the next closing ] specifies a /collection
- Character ranges can be represented with a
- ; for example a letter a,b,c,or the number 1 can be matched with [1a-c] . Negate the collection with [^ instead of [ ; for example [^1a-c] matches any character except a,or 1.
{#} is used for repetition
/foo.{2} will match foo and the two following characters
is not required on the closing } so /foo.{2} will do the same thing.
(foo) makes a backreference to foo. Parenthesis without escapes are literally matched. Here the is required for the closing )
替换
r is newline,n is a null byte (0x00).
&; is ampersand (& is the text that matches the search pattern).
|