从 Bash 命令在文本文件中查找和替换
查找和替换给定输入字符串的最简单方法是什么,比如 abc
,然后替换为另一个字符串,比如文件 /中的
?XYZ
tmp/file.txt
What's the simplest way to do a find and replace for a given input string, say abc
, and replace with another string, say XYZ
in file /tmp/file.txt
?
我正在编写一个应用程序并使用 IronPython 通过 SSH 执行命令 —但我不太了解 Unix,也不知道该找什么.
I am writting an app and using IronPython to execute commands through SSH — but I don't know Unix that well and don't know what to look for.
我听说 Bash 除了作为命令行界面之外,还是一种非常强大的脚本语言.所以,如果这是真的,我假设你可以执行这样的操作.
I have heard that Bash, apart from being a command line interface, can be a very powerful scripting language. So, if this is true, I assume you can perform actions like these.
我可以用 bash 来实现吗?实现我的目标的最简单的(一行)脚本是什么?
Can I do it with bash, and what's the simplest (one line) script to achieve my goal?
最简单的方法是使用 sed(或 perl):
The easiest way is to use sed (or perl):
sed -i -e 's/abc/XYZ/g' /tmp/file.txt
由于 -i
选项,它将调用 sed 进行就地编辑.这可以从 bash 调用.
Which will invoke sed to do an in-place edit due to the -i
option. This can be called from bash.
如果你真的只想使用 bash,那么下面的方法可以工作:
If you really really want to use just bash, then the following can work:
while read a; do
echo ${a//abc/XYZ}
done < /tmp/file.txt > /tmp/file.txt.t
mv /tmp/file.txt{.t,}
这会遍历每一行,进行替换,然后写入临时文件(不想破坏输入).最后的移动只是暂时移动到原来的名字.
This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name.
sed -i '' 's/abc/XYZ/g'/tmp/file.txt
(原因见下方评论)