Replace string2 by string3 where string1 is found in line

Hello,
My aim is to search string1 in all lines. When found, find and replace string2 by string3 if possible.

TextFile:

Here is my first line
Second line with string1 & string2
Not last line but it contains string1

Expected output:

Here is my first line
The second line with string1 & string3
Not last line but it contains string1

I tested below command:

grep "string1" TextFile | xargs sed -i 's/string2/string3/g'

I feel really lucky if you would shed light on this question.

Many thanks
Boris

With your grep pipeline, any line in TextFile containing the string string1 will be treated by xargs as the name of a file to be passed as an operand to sed . I fail to see how that would meet your ambiguous requirements no matter how I try to guess at what you mean.

And, since you haven't told us what operating system and shell you're using, we have no way of knowing whether or not the non-standard sed -i option is supported on your system.

If sed on your system does have a -i option and what you want to do is replace every occurrence of the string string2 with the string string3 on every line that contains the string string1 and leave lines that do not contain the string string1 unchanged, the obvious way to do what you want is:

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

and a safer, portable way to do that would be to use:

sed '/string1/s/string2/string3/g' "TextFile" > "TextFile.$$" && cp "TextFile.$$" "Textfile"; rm -f "TextFile.$$"
awk ' /string1/ {gsub (/string2/, "string3")} 1' file 

Dear Don,
Thanks for your reply.
I am running under ubuntu 18.04.
Let me specificially give an example for my case:

Let's say, string1 is keyword , string2 is .
I wish to remove dot sign when keyword is found in line:
I do:

sed '/keyword/s/.//g' TextFile > output

Double quotes is also not sorting it out.

There is no below line in output file:

Second line with keyword &. 

You can try like this:

STR1="string1"
STR2="string2"
STR3="string3"
awk '$0 ~ STR1 {gsub (STR2, STR3); } 1' STR1="$STR1" STR2="$STR2" STR3="$STR3"  file

However, if your search string2 has a regex special character in it, you need to escape it, like

STR1="keyword"
STR2="\."
STR3=""

Of course there isn't. In the command:

sed '/keyword/s/.//g'

keyword and . are not just strings, they are regular expressions. And the regular expression . matches any single character. And globally replacing every character in a line with an empty string changes every line that contains keyword into an empty line.

To match a literal period character, try:

sed '/keyword/s/\.//g' TextFile > output

or:

sed '/keyword/s/[.]//g' TextFile > output

Hello Don,
Voila...
Both gives the expected output.

Thanks a lot!
Boris