1

I use the following command to replace a specific string (replace string1 with string2) in lines containing another string (string3).

  sed -i '/string3/ s/string1/string2/' file.txt

PROBLEM...

The command above works fine - BUT - it only replaces string1 with string2 on the first occurrance of string1 in the line containing string3.

I have to run the command multiple times to make sure all occurrances of string1 are replaced.

  sed -i '/string3/ s/string1/string2/' file.txt
  sed -i '/string3/ s/string1/string2/' file.txt
  sed -i '/string3/ s/string1/string2/' file.txt

Is there a way to replace all occurances of string1 in a line containing string3 in a single step?

That could help me shrink my bash file.

Big thanks.

  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you! – Jeff Schaller Nov 18 '17 at 14:35
4

All you need to do is to add sed's "global replacement" flag to the end:

sed -i '/string3/ s/string1/string2/g' file.txt
  • Thanks - That simple? - I was wondering why the g wasn't there in the posts I was reading. Go figure. Again, thanks. – speld_rwong Jul 27 '17 at 16:06
  • Depends entirely on what you want to have happen! Glad it helped; don't forget the checkmark if it did solve your problem. – Jeff Schaller Jul 27 '17 at 16:08
1

For completeness, while the obvious solution in this case is to add the g flag, there are some cases where you may want to run the s/string1/string2/ (or s/string1/string2/g) command several times.

For instance if instead of string2, you have str, on an input like:

string1ing1

s/string1/str/g would result to:

string1

If you wanted str instead, you'd need another s/string1/str/g. With sed, there's an idiomatic way to run a substitution as long as it succeeds using the t command:

sed '
  /string3/{
    :1
    s/string1/string2/
    t1
  }'

t branches to the :1 label only if there has been a successful s command.

0

while question is tagged with sed and given perfect answer above, but here is awk version for those will looking it.

awk '/string3/{gsub("string1", "string2", $0)}1' infile.txt 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.