1

Consider the following text:

alpha0_inc0 : beta0_inc0_term
alpha1_inc1 : beta1_inc1_term
alpha2_inc2 : beta2_inc1_term
alpha3_inc3 : beta3_inc0_term

I want to replace text matching the regex inc\d with the match+new. The expected result should be:

alpha0_inc0_new : beta0_inc0_new_term
alpha1_inc1_new : beta1_inc1_new_term
alpha2_inc2_new : beta2_inc1_new_term
alpha3_inc3_new : beta3_inc0_new_term

inc\d matches inc0, inc1, etc. The issue is I want to just add a new term to all the regex matches.

One way to do this would be to use:

:%s/inc0/inc0_new/g
:%s/inc1/inc1_new/g
:%s/inc2/inc2_new/g
:%s/inc3/inc3_new/g

But this gets tedious quickly. Is there a better way to achieve this?

0

Use & in your replacement string, which replaces the whole match, so you can easily add to it.

:%s/inc\d/&_new/g

See :help :s& for more special sequences you can use in substitutions.

In particular, if you want to use parts of the match, you can group parts with pairs of \( and \) and refer back to them with \1, \2, etc.

Finally, for most flexibility, you can use \= which allows you to enter an expression and use VimL to generate your replacement string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.