In vim we can substitute with an sub-replace-expression
. When the substitute string starts with \=
the remainder is interpreted as an expression.
e.g. with text:
bar
bar
and substitute command:
:%s/.*/\='foo \0'/
gives unexpected results:
foo \0
foo \0
instead of:
foo bar
foo bar
The question is: How to evaluate expression with matched pattern in substitute?
When you use a sub-replace-expression, the normal special replacements like &
and \1
don't work anymore; everything is interpreted as a Vimscript expression. Fortunately, you can access the captured submatches with submatches()
, so it becomes:
:%s/.*/\='foo ' . submatch(0)/
You need :%s/.*/foo \0/
With :%s/.*/\='foo \0'/
you evaluate 'foo \0'
but that's a string and it evaluates to itself.
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