9

How do I replace every number n that matches a certain pattern with n+1? E.g. I want to replace all numbers in a line that are in brackets with the value+1.

1 2 <3> 4 <5> 6 7 <8> <9> <10> 11 12

should become

1 2 <4> 4 <6> 6 7 <9> <10> <11> 11 12
pfnuesel
  • 14,093
  • 14
  • 58
  • 71

2 Answers2

13

%s/<\zs\d\+\ze>/\=(submatch(0)+1)/g

By way of explanation:

%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

Edit: If you only want to replace in specific line, move your cursor on that line, and execute

s/<\zs\d\+\ze>/\=(submatch(0)+1)/g

or use

LINENUMs/<\zs\d\+\ze>/\=(submatch(0)+1)/g

(replace LINENUM with the actual line number, eg. 13)

cogitovita
  • 1,685
  • 1
  • 15
  • 15
  • Could you explain the pattern? I think `%s` is the replace command, but what is the rest? – mliebelt Oct 05 '13 at 08:30
  • @cogitovita Watch out: %s will replace all occurrences in the file, not only in the current line. Not specifying % will make the command work only on the current line. – el_tenedor Oct 05 '13 at 08:37
4

In vim you can increment (decrement) the numeric digit on or after the cursor by pressing

NUMBER<ctrl-a>      to add NUMBER to the digit 
(NUMBER<ctrl-x>      to substract NUMBER from the digit)

If only incrementing (decrementing) by one you don't need to specify NUMBER. In your case I would use a simple macro for this:

qaf<<ctrl-a>q

100<altgr-q>a

Here a brief explanation of the macro: It uses the find (f) commant to place the cursor on the opening < bracket. It is not necessary to position the cursor on the digit. When press the number on the cursor or the nearest number after the cursor will get incremented.

If you want an even shorter series of commands you can position your curser ONCE by pressing f<, increment the number with ctrl-a and then just repeatedly press ;.. The ; command repeats the last cursor movement i.e. the find command. The . command repeats the last text changing command.

Check out this link for further information or use the built in documentation: h: ctrl-a.

el_tenedor
  • 644
  • 1
  • 8
  • 19