Replace string2 by string3 where string1 is found in line

I found this in the forum that searches a file for string1, substitute all occurrences of string2 with string3.
(Title: Replace string2 by string3 where string1 is found in line)

>> sed -i '/string1/s/string2/string3/g' TextFile

How will I perform the same sed command and only substitute string3 to the first occurrence of string2 right after the occurrence of string1 in same line?

File content:
Line contains string1 with string2 with other data on this line and another string2

Output:

Line contains string1 with string3 with other data on this line and another string2

Thanks.

So removing "g" would then only replace the first occurrence.

2 Likes

Thanks!

In another example below, how about substituting string3 ONLY to the first occurrence of string2, right after the occurrence of string1? The pattern I am looking for is string1 and just need to replace only the string2 immediately after the pattern.

File content:
Line contains string2 and string1 with another string2 with other data on this line and yet another string2

Output:

Line contains string2 and string1 with another string3 with other data on this line and yet another string2

To replace the 2nd string2 is easy

sed '/string1/s/string2/string3/2' TextFile

But this searches string1 throughout the line, then starts over and substitutes the 2nd string2 from the beginning of the line.
If you really want the 1st string2 after string1, then you have to include string1 into the substitution command.
I suggest perl and its minimum match. perl -pe works a bit like sed:

perl -pe 's/(string1.*?)string2/${1}string3/' TextFile

The $1 refers to what was captured in the 1st ( ) group.
The .*? is a non-greedy .* (any character any times).