Search code examples
vimvi

Replace string only in matched search in Vim


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?


Solution

  • 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