Reputation: 5408
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?
Upvotes: 4
Views: 579
Reputation: 172768
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)/
Upvotes: 8
Reputation: 29427
You need :%s/.*/foo \0/
With :%s/.*/\='foo \0'/
you evaluate 'foo \0'
but that's a string and it evaluates to itself.
Upvotes: 1
Reputation: 2574
You don't need to evaluate any expression for that, use a regex group and proper escapes
:%s /\(.*\)/foo \1/
Upvotes: 0