在Vim命令行中使用Ctrl-A增加一个数字

时间:2010-01-14 04:36:37

标签: vim

在正常模式下(在Vim中)如果光标在数字上,按 Ctrl - A 将数字增加1.现在我想做同样的事情,但是从命令行。具体来说,我想去某些第一个字符是数字的行,然后递增它,即我想运行以下命令:

:g/searchString/ Ctrl-A

我尝试在宏(例如a)中存储 Ctrl - A ,并使用:g/searchString/ @a,但是我收到错误消息:

  

E492:不是编辑命令^ A

有什么建议吗?

3 个答案:

答案 0 :(得分:26)

您必须使用normal命令模式下执行普通模式命令

:g/searchString/ normal ^A

请注意,您必须按 Ctrl - V Ctrl - A 才能获得{{1} } character。

答案 1 :(得分:10)

与CMS发布的:g//normal技巧一样,如果您需要使用更复杂的搜索来执行此操作,而不仅仅是在行的开头找到一个数字,那么您可以执行以下操作:

:%s/^prefix pattern\zs\d\+\zepostfix pattern/\=(submatch(0)+1)

作为解释:

:%s/X/Y            " Replace X with Y on all lines in a file
" Where X is a regexp:
^                  " Start of line (optional)
prefix pattern     " Exactly what it says: find this before the number
\zs                " Make the match start here
\d\+               " One or more digits
\ze                " Make the match end here
postfix pattern    " Something to check for after the number (optional)

" Y is:
\=                 " Make the output the result of the following expression
(
    submatch(0)    " The complete match (which, because of \zs and \ze, is whatever was matched by \d\+)
    + 1            " Add one to the existing number
)

答案 2 :(得分:0)

我相信你可以在命令行上用vim做到这一点。但这是另一种选择,

$ cat file
one
2two
three

$ awk '/two/{x=substr($0,1,1);x++;$0=x substr($0,2)}1' file #search for "two" and increment
one
3two
three