Korsan
Korsan

Reputation: 23

Substitute both the beginning and end of every occurrence of a string with vim

I have more than a hundred of occurrences of the string ?dep= followed by two numbers. So it goes like ?dep=01, ?dep=02, ?dep=03, etc. I need to change the string but keep the numbers at the same time, so for example

?dep=01

needs to become

{{ path('annonce-index', {departement: 01}) }}

How can I do that with the substitute command in vim?

Upvotes: 2

Views: 49

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172520

This can be done with a simple capture group: match both the part that gets removed (?dep=) and the part that will be kept (\d\d), but enclose the latter in \(...\) to capture it. Then, in the replacement, refer to the first capture via \1:

:%s/?dep=\(\d\d\)/{{ path('annonce-index', {departement: \1}) }}/g

The :% applies this to the entire buffer, the /g flag applies this to multiple matches in a single line. Read :help /\( and :help :substitute for more information.

Upvotes: 6

Related Questions