How to replace multiple patterns at once with sed?

DaniloNC picture DaniloNC · Oct 26, 2014 · Viewed 339.1k times · Source

Suppose I have 'abbc' string and I want to replace:

  • ab -> bc
  • bc -> ab

If I try two replaces the result is not what I want:

echo 'abbc' | sed 's/ab/bc/g;s/bc/ab/g'
abab

So what sed command can I use to replace like below?

echo abbc | sed SED_COMMAND
bcab

EDIT: Actually the text could have more than 2 patterns and I don't know how many replaces I will need. Since there was a answer saying that sed is a stream editor and its replaces are greedily I think that I will need to use some script language for that.

Answer

ooga picture ooga · Oct 26, 2014

Maybe something like this:

sed 's/ab/~~/g; s/bc/ab/g; s/~~/bc/g'

Replace ~ with a character that you know won't be in the string.