Vim: Replace n with n + 1

How to replace each number n that matches a specific pattern with n+1 ? For example. I want to replace all the numbers in a line in brackets with a value of + 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 
+8
vim replace
source share
2 answers

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

As an 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 want to replace only on a specific line, move the cursor to 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, e.g. 13)

+11
source share

In vim, you can increase (decrease) a 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 you only increase (decrease) by one, you do not need to specify NUMBER. In your case, I would use a simple macro for this:

 qaf<<ctrl-a>q 100<altgr-q>a 

Here is a brief explanation of the macro: it uses the find (f) command to place the cursor on the opening <bracket. There is no need to position the cursor on a digit. When you click the number on the cursor or the nearest number after the cursor increases.

If you want an even shorter series of commands, you can position your ONCE cursor by pressing f< , increase the number with ctrl-a , and then just press ;. several times ;. . Team repeats the last cursor move, that is, the find command. Team repeats the last text change command.

Refer to this link for more information or use the built-in documentation: h: ctrl-a .

+4
source share

All Articles