我是Vim的初学者,我一直在阅读有关替代的内容,但我还没有找到这个问题的答案.
假设我在文件中有一些数字,如下所示:
1
2
3
Run Code Online (Sandbox Code Playgroud)
我想得到:
(1)
(2)
(3)
Run Code Online (Sandbox Code Playgroud)
我认为命令应该类似于:s:\d\+:.......
.另外,:s/foo/bar
和之间的区别是:s:foo:bar
什么?
谢谢
rom*_*inl 12
这是一个替代的,稍微不那么详细的解决方案:
:%s/^\d\+/(&)
Run Code Online (Sandbox Code Playgroud)
说明:
^ anchors the pattern to the beginning of the line
\d is the atom that covers 0123456789
\+ matches one or more of the preceding item
& is a shorthand for \0, the whole match
Run Code Online (Sandbox Code Playgroud)
Let me address those in reverse.
第一::s/foo/bar
和之间没有区别:s:foo:bar
; 无论你使用什么分隔符s
,vim都会期望你从那时开始使用.例如,如果你有一个涉及大量斜杠的替换,这可能会很好.
对于第一个:对当前行的第一个数字执行此操作(假设没有逗号,小数位等),您可以执行此操作
:s:\(\d\+\):(\1)
Run Code Online (Sandbox Code Playgroud)
该\(...\)
不会改变匹配-更确切地说,它告诉Vim记住任何匹配的里面是什么,并储存起来.第一个\(...\)
存储在\1
第二个中\2
,等等.因此,当您进行更换时,您可以参考\1
以获取数字.
如果要更改当前行上的所有数字,请将其更改为
:s:\(\d\+\):(\1):g
Run Code Online (Sandbox Code Playgroud)
如果要更改所有行上的所有数字,请将其更改为
:%s:\(\d\+\):(\1):g
Run Code Online (Sandbox Code Playgroud)