19

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 command line. 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?

Mateusz Piotrowski
  • 6,087
  • 9
  • 44
  • 71
user10
  • 1,856
  • 5
  • 18
  • 26

3 Answers3

30

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.

Christian C. Salvadó
  • 723,813
  • 173
  • 899
  • 828
11

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
)
DrAl
  • 64,451
  • 10
  • 98
  • 103
0

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
  • 286,686
  • 52
  • 238
  • 332