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.txt
on Unix. I'd like to produce another file file2.txt
, in which I replace all occurrences of apple-pie
with apple_pie
. What command can I use?
我file1.txt
在 Unix 上有一个文本文件。我想产生另一个文件file2.txt
,在其中我代替所有出现的apple-pie
用apple_pie
。我可以使用什么命令?
采纳答案by Chris Seymour
Use sed
to do a global substitution on file1.txt
and redirect the output to file2.txt
:
用sed
做全局替换上file1.txt
和输出重定向到file2.txt
:
sed 's/apple-pie/apple_pie/g' file1.txt > file2.txt
回答by javaPlease42
sed
has better performance than awk
but 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"