Search and replace: how to use a matched expression in a "" substitute expression?
Search and replace: how to use a matched expression in a "" substitute expression?
Here's a little puzzle for you Vim specialists:
Say I have a random text file containing the following lines:
This is foo1 and bar1: it has bar1 and foo1, or foo1 and bar1 if you prefer.
foo1 is not exactly like bar1.
bar1 has the same number of letters as foo1 and the same trailing number.
I want to search and replace all instances of foo1 and bar1 in all the lines in the file so the number after foo and bar increments at each matched line, so the file becomes:
This is foo1 and bar1: it has bar1 and foo1, or foo1 and bar1 if you prefer.
foo2 is not exactly like bar2.
bar3 has the same number of letters as foo3 and the same trailing number.
I can search all instances of foo1 and bar1 and replace them with foo2 and bar2 easily enough with:
:%s/\(foo\|bar\)1/\12/g
(the file then becomes:
This is foo2 and bar2: it has bar2 and foo2, or foo2 and bar2 if you prefer
foo2 is not like bar2
bar2 has the same number of letters as foo2 and the same number
)
and I can search foo1 and replace it with foo1, foo2, foo3, foo4... line-wise with a vimscript:
:let i=1 | %g/foo1/ s//\='foo' . i/g | let i+=1
(the file then becomes:
This is foo1 and bar1: it has bar1 and foo1, or foo1 and bar1 if you prefer
foo2 is not like bar1
bar1 has the same number of letters as foo3 and the same number
)
The question is, how can I do both?
The problem is the \= substitute operator, that expects (and evaluates) an expression: I need it to expand i in the substitution pattern.
The problem is, it has to be alone in the substitution pattern (i.e. I can't do s//\1\=i/, which would first expand \1 into foo or bar, then expand \=i into the value of i, and which is what I really want to do).
So my question is, what's the syntax to expand \1 in the \= expression? I tried looking up the syntax for \= but the official documentation is thin on details and I couldn't find how to do it - or even if it's doable at all.
Any idea?