Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Replace n with n+1

Tags:

replace

vim

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
like image 404
pfnuesel Avatar asked Oct 05 '13 08:10

pfnuesel


2 Answers

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

like image 178
cogitovita Avatar answered Sep 28 '22 02:09

cogitovita


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.

like image 26
el_tenedor Avatar answered Sep 28 '22 02:09

el_tenedor