在linux中查找固定字符串并替换

时间:2016-01-28 06:06:29

标签: linux shell sed

我有一个文件input.txt这个文件的内容是:

111,sumit

222,sumit

333,sumit_gupta

444,sumit_gupta

现在,我正在编写一个脚本来查找和替换in​​put.txt中的关键字:

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

我想用hello替换sumit,hi和sumit_gupta用bye替换。但是当我运行脚本时。我得到的输出是:

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

111,hello,hi

222,hello,hi

333,hello,hi_gupta

444,hello,hi_gupta

然而,所需的输出应该是:

111,hello,hi

222,hello,hi

333,bye

444,bye

请告诉我如何实现这个目标?

2 个答案:

答案 0 :(得分:1)

第一个sed会更改sumit的所有实例。先做第二个。

答案 1 :(得分:0)

试试这个方法

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

<强>输出:

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

注意:

\ b作为单词边界,它将匹配确切的单词