Linux 在bash中用另一个词替换一个词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9142131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:23:14  来源:igfitidea点击:

Replace a word with another in bash

linuxbashterminalsh

提问by reza

I want to change all of the words in a text who matches a certain word with another one in bourne shell. For example:

我想更改文本中将某个单词与 bourne shell 中的另一个单词匹配的所有单词。例如:

hello sara, my name is sara too.

becomes:

变成:

hello mary, my name is mary too.

Can anybody help me?
I know that grep find similar words but I want to replace them with other word.

有谁能够帮助我?
我知道 grep 会找到相似的词,但我想用其他词替换它们。

采纳答案by anubhava

Pure bash way:

纯bash方式:

before='hello sara , my name is sara too .'
after="${before//sara/mary}"
echo "$after"

OR using sed:

或使用 sed:

after=$(sed 's/sara/mary/g' <<< "$before")
echo "$after"

OUTPUT:

输出:

hello mary , my name is mary too .

回答by Niklas B.

You can use sedfor that:

您可以使用sed

$ sed s/sara/mary/g <<< 'hello sara , my name is sara too .'
hello mary , my name is mary too .

Or if you want to change a file in place:

或者,如果您想就地更改文件:

$ cat FILE
hello sara , my name is sara too .
$ sed -i s/sara/mary/g FILE
$ cat FILE
hello mary , my name is mary too .

回答by Wes Hardaker

You can use sed:

您可以使用 sed:

# sed 's/sara/mary/g' FILENAME

will output the results. The s/// construct means search and replace using regular expressions. The 'g' at the end means "every instance" (not just the first).

将输出结果。s/// 构造意味着使用正则表达式进行搜索和替换。最后的“g”表示“每个实例”(不仅仅是第一个)。

You can also use perl and edit the file in place:

您还可以使用 perl 并就地编辑文件:

# perl -p -i -e 's/sara/mary/g;' FILENAME

回答by jaypal singh

Or awk

或者 awk

awk '{gsub("sara","mary")}1' <<< "hello sara, my name is sara too."