Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple patterns at once with sed?

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.

like image 504
DaniloNC Avatar asked Oct 26 '14 01:10

DaniloNC


People also ask

How do you put multiple patterns in sed?

Use multiple patterns at once with SedLook out for the semicolon(;) to add more patterns within the single command.

Can sed match multiple lines?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.


2 Answers

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.

like image 66
ooga Avatar answered Sep 26 '22 10:09

ooga


I always use multiple statements with "-e"

$ sed -e 's:AND:\n&:g' -e 's:GROUP BY:\n&:g' -e 's:UNION:\n&:g' -e 's:FROM:\n&:g' file > readable.sql

This will append a '\n' before all AND's, GROUP BY's, UNION's and FROM's, whereas '&' means the matched string and '\n&' means you want to replace the matched string with an '\n' before the 'matched'

like image 29
Paulo Henrique Lellis Gonalves Avatar answered Sep 26 '22 10:09

Paulo Henrique Lellis Gonalves