Linux 替换文件 Unix 中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13663696/
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
Replacing string in file Unix
提问by Mika H.
I have a text file file1.txton Unix. I'd like to produce another file file2.txt, in which I replace all occurrences of apple-piewith apple_pie. What command can I use?
我file1.txt在 Unix 上有一个文本文件。我想产生另一个文件file2.txt,在其中我代替所有出现的apple-pie用apple_pie。我可以使用什么命令?
采纳答案by Chris Seymour
Use sedto do a global substitution on file1.txtand redirect the output to file2.txt:
用sed做全局替换上file1.txt和输出重定向到file2.txt:
sed 's/apple-pie/apple_pie/g' file1.txt > file2.txt
回答by javaPlease42
sedhas better performance than awkbut both will work for this search and replace. Reference
sed性能比awk但两者都适用于此搜索和替换。参考
If you put the commands in a script (e.g., ksh, sh) then here is the syntax:
如果将命令放在脚本中(例如 ksh、sh),则语法如下:
awk '{gsub(/apple-pie/,"apple_pie");print}' "file1.txt" > "file2.txt"
sed -e 's/apple-pie/apple_pie/g' "file1.txt" > "file2.txt"

