sumit gupta
sumit gupta

Reputation: 3

Find fixed string and replace in linux

I have a file input.txt the contents of this file are:

111,sumit

222,sumit

333,sumit_gupta

444,sumit_gupta

Now, I am writing a script to find and replace the keywords in input.txt:

#!/bin/bash
sed -i -e 's/sumit/hello,hi/g' input.txt
sed -i -e 's/sumit_gupta/bye/g' input.txt

I wanted to replace sumit with hello,hi and sumit_gupta with bye. But when I am running the script. The output I am getting is:

[sumit.gupta@abc]$ cat input.txt

111,hello,hi

222,hello,hi

333,hello,hi_gupta

444,hello,hi_gupta

whereas, desired output required should be:

111,hello,hi

222,hello,hi

333,bye

444,bye

Kindly let me know how to achieve this?

Upvotes: 0

Views: 148

Answers (2)

Kalanidhi
Kalanidhi

Reputation: 5092

Try this method

#!/bin/bash
sed -i -e 's/\bsumit\b/hello,hi/g' input.txt
sed -i -e 's/\bsumit_gupta\b/bye/g' input.txt

Output:

111,hello,hi
222,hello,hi
333,bye
444,bye

Note:

\b as a word boundary , It will match exact word

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86744

The first sed changes all instances of sumit. Do the second one first.

Upvotes: 1

Related Questions