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 without 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

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.