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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With