如何用 替换n
与特定模式匹配的每个数字n+1
?例如,我想用值+1 替换括号中的所有数字。
1 2 <3> 4 <5> 6 7 <8> <9> <10> 11 12
应该成为
1 2 <4> 4 <6> 6 7 <9> <10> <11> 11 12
%s/<\zs\d\+\ze>/\=(submatch(0)+1)/g
通过解释:
%s " replace command
"""""
< " prefix
\zs " start of the match
\d\+ " match numbers
\ze " end of the match
> " suffix
"""""
\= " replace the match part with the following expression
(
submatch(0) " the match part
+1 " add one
)
"""""
g " replace all numbers, not only the first one
编辑:如果您只想替换特定行,请将光标移到该行上,然后执行
s/<\zs\d\+\ze>/\=(submatch(0)+1)/g
或使用
LINENUMs/<\zs\d\+\ze>/\=(submatch(0)+1)/g
(替换LINENUM
为实际的行号,例如 13)
在 vim 中,您可以通过按
NUMBER<ctrl-a> to add NUMBER to the digit
(NUMBER<ctrl-x> to substract NUMBER from the digit)
如果只增加(减少)1,则不需要指定 NUMBER。在你的情况下,我会为此使用一个简单的宏:
qaf<<ctrl-a>q
100<altgr-q>a
这里对宏进行简要说明:它使用 find (f) 命令将光标放在左 < 括号上。不必将光标定位在数字上。当按光标上的数字或光标后最接近的数字时,将递增。
如果您想要更短的命令系列,您可以通过按一次定位您的光标f<
,增加数字,ctrl-a
然后重复按;.
。该;
命令重复上一次光标移动,即 find 命令。该.
命令重复上一个文本更改命令。
查看此链接以获取更多信息或使用内置文档:h: ctrl-a
.