Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim search and replace by decrementing back-reference?

Tags:

regex

replace

vim

Given the following text in Vim:

[2] [3] [4]

I want to perform a search and replace and produce the following:

[1] [2] [3]

I know how to extract out the numbers using back-reference via search and replace:

:%s/\[\(\d\)\]/[\1]/g

But now the question is how do you go about decrementing the value of \1.

Any ideas?

like image 675
Timothy Kim Avatar asked May 18 '09 04:05

Timothy Kim


2 Answers

Try

:%s/\[\(\d\+\)\]/\=join(['[', submatch(1) - 1, ']'], '')/g

EDIT: I added a \+ after \d in case you wanted to match more than single digit numbers.

See :help sub-replace-special

like image 54
sykora Avatar answered Oct 28 '22 03:10

sykora


When you use \zs and \ze to anchor the number inside the brackets without matching them, the substitution becomes simpler, because you don't need to concatenate in the replacement:

:%s/\[\zs\d\+\ze]/\=submatch(0)-1/g
like image 21
Ingo Karkat Avatar answered Oct 28 '22 03:10

Ingo Karkat