How to replace multiple patterns at once with sed

replacesedsyntax

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.

Best Answer

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.