Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string only in matched search in Vim

Tags:

vim

vi

I know you can replace certain patterns in a file using Vim:

:%s/<pattern>/<replacement>/g

What I want to do is to carry out a pattern replacement ONLY where a secondary search matches, e.g.: if I had the following lines in my file:

00_sub_5_train
01_sub_6_train
02_sub_5_train
03_sub_9_train
04_sub_8_train
05_sub_5_train
06_sub_5_train

I would want to carry out: :%s/train/not_train/g ONLY on the lines where the string 'sub_5' is found such that what remains is:

00_sub_5_not_train
01_sub_6_train
02_sub_5_not_train
03_sub_9_train
04_sub_8_train
05_sub_5_not_train
06_sub_5_not_train

Is this possible?

like image 295
PedsB Avatar asked Mar 21 '26 00:03

PedsB


1 Answers

You can directly apply the pattern as below. You can fully apply the pattern with sub_5_train

:%s/sub_5_train/sub_5_not_train/g

Based on comment, if you will be having different content post sub_5, you can go for conditional replace like below:

:g/sub_5/ s/train/not_train

Here, if we find sub_5, we are going for replace for that line only.

Basically, I am trying to utilize g command like below. Here, for cmd, I am using substitute command. more on vim g command

:[range]g/pattern/cmd
like image 192
Venkataraman R Avatar answered Mar 24 '26 23:03

Venkataraman R