tags:

views:

285

answers:

3

Hi,

In normal mode (in vim) if the cursor is on a number, hitting Ctrl-A increments the number by 1. Now I want to do the same thing, but from the commandline. Specifically, I want to go to certain lines whose first character is a number, and increment it. i.e. I want to run the following command:

:g/searchString/ Ctrl-A

I tried to store Ctrl-A in a macro (say a), and using :g/searchString/ @a, but I get an error E492: Not an editor command ^A. Any suggestions?

Thanks! Gaurav

+7  A: 

You have to use normal to execute normal mode commands in command mode:

:g/searchString/ normal ^A

Note that you have to press Ctrl-VCtrl-A to get the ^A character.

CMS
Didn't know this! Thanks a lot.
gveda
Been using vim for years and never came across "normal" -- kool
James Anderson
@James: Beauty of the unknown :) Vim surprises like no other software!
Vijay Dev
A: 

i am sure you can do that with vim on the command line. But here's an alternative,

$ 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
ghostdog74
A: 

As well as the :g//normal trick posted by CMS, if you need to do this with a more complicated search than just finding a number at the start of the line, you can do something like this:

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

By way of explanation:

:%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
)
Al