Abhishek Das
Abhishek Das

Reputation: 17

How to ignore few characters in search and replace in vim editor

I want to do something like this in the vim editor:

:%s/SETR P:LL../SETR P:LH../g

There are multiple lines which start with SETR P: in my file where I want to replace the second L with an H while the remaining two letters in that line will be the same as it was before.

Say if it was earlier SETR P:LLHC
After replacing it would be SETR P:LHHC

Can I do it in one instruction with the vim editor?

Upvotes: 0

Views: 1684

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

It looks like you could just settle for:

:%s/SETR P:LL/SETR P:LH/

To exclude the preceding text from the match you can use the \@<= look-behind assertion or \zs:

:%s/\(SETR P:L\)\@<=L/H/
:%s/SETR P:L\zsL/H/

Similarly, for excluding the subsequent text from the match \@= and \ze can be used.

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172510

This is commonly done with capture groups. Capture the part of the source pattern that you want to re-include in the replacement via \(...\). Then, in the replacement, you can refer to that part via \1 (and following via \2, and so on):

:%s/SETR P:LL\(..\)/SETR P:LH\1/g

This is documented under :help /\(.


An alternative here would be to end the match after the LL, using \ze (match end). The rest of the pattern (..) is still checked, but it is not part of the match.

:%s/SETR P:LL\ze../SETR P:LH/g

By the way, your pattern will also happily match longer ends, e.g. SETR P:LLHHHHHHHH. If you need to limit the extension to two letters, use ..\> (keyword boundary) or ..\A\@= (non-alphabetic lookahead).

Upvotes: 2

Related Questions