Wednesday, December 19, 2012

SED find and replace multiple search patterns

Q. I have a word abc and cde and I want to replace them both with xyz. How can I do that in Shell scripting?

We can not do this with out using sed command. Below are the ways you can do that.

Below example will try to replace abc or cde with xyz. I used regexp '|' to accomplish this task. -r is for enabling regexp and -i for inserting the changes in to the file.
sed -ri 's/abc|cde/xyz/g' filename

Some more examples on replacing multiple words/char. In below example we can replace either a or b with d

sed -i 's/[ab]/d/g' filename

I want to replace swapon and swapoff words with just word "free"

sed -r 's/swap(on|off)/free/g' filename
In order to understand () and | we have know about regexp please click here to know more about regexp

Below is bit odd way to do the multiple word changes using sed.

sed 's/abc/get/g;s/def/get/g' filename
sed -e 's/abc/get/g' -e 's/def/get/g' filename


Post a Comment