views:

1323

answers:

2

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?

+7  A: 

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

sykora
Awesome! Do you know of any good documentations in using \= in search and replace?
Highwind
Try :help sub-replace-expression
sykora
A: 

Try this:

%s:\d:\r&\r:g

Then

s/\d/\=submatch(0)-1/

And now you need to join the lines.

Zsolt Botykai