Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute with an expression and matched pattern

Tags:

vim

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?

like image 441
hawk Avatar asked Oct 18 '25 13:10

hawk


2 Answers

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)/
like image 192
Ingo Karkat Avatar answered Oct 21 '25 04:10

Ingo Karkat


You need :%s/.*/foo \0/

With :%s/.*/\='foo \0'/ you evaluate 'foo \0' but that's a string and it evaluates to itself.

like image 30
user2314737 Avatar answered Oct 21 '25 05:10

user2314737



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!