查找和替换一个给定的输入字符串,比如abc,并替换成另一个字符串,比如文件/tmp/file.txt中的XYZ,最简单的方法是什么?

我正在编写一个应用程序,并使用IronPython通过SSH执行命令-但我不太了解Unix,也不知道该寻找什么。

我听说Bash除了是一种命令行界面外,还可以是一种非常强大的脚本语言。所以,如果这是真的,我假设你可以执行这样的操作。

我可以用bash实现它吗?要实现我的目标,最简单的(一行)脚本是什么?


当前回答

你可以使用sed:

sed -i 's/abc/XYZ/gi' /tmp/file.txt

如果你不知道你的文件名,你可以使用find和sed:

find ./ -type f -exec sed -i 's/abc/XYZ/gi' {} \;

在所有Python文件中查找并替换:

find ./ -iname "*.py" -type f -exec sed -i 's/abc/XYZ/gi' {} \;

其他回答

我在其他帖子中发现了这个帖子,我认为它包含了最完整的答案,所以我也添加了我的答案:

sed and ed are so useful...by hand. Look at this code from @Johnny: sed -i -e 's/abc/XYZ/g' /tmp/file.txt When my restriction is to use it in a shell script, no variable can be used inside in place of "abc" or "XYZ". The BashFAQ seems to agree with what I understand at least. So, I can't use: x='abc' y='XYZ' sed -i -e 's/$x/$y/g' /tmp/file.txt #or, sed -i -e "s/$x/$y/g" /tmp/file.txt but, what can we do? As, @Johnny said use a while read... but, unfortunately that's not the end of the story. The following worked well with me: #edit user's virtual domain result= #if nullglob is set then, unset it temporarily is_nullglob=$( shopt -s | egrep -i '*nullglob' ) if [[ is_nullglob ]]; then shopt -u nullglob fi while IFS= read -r line; do line="${line//'<servername>'/$server}" line="${line//'<serveralias>'/$alias}" line="${line//'<user>'/$user}" line="${line//'<group>'/$group}" result="$result""$line"'\n' done < $tmp echo -e $result > $tmp #if nullglob was set then, re-enable it if [[ is_nullglob ]]; then shopt -s nullglob fi #move user's virtual domain to Apache 2 domain directory ...... As one can see if nullglob is set then, it behaves strangely when there is a string containing a * as in: <VirtualHost *:80> ServerName www.example.com which becomes <VirtualHost ServerName www.example.com there is no ending angle bracket and Apache2 can't even load. This kind of parsing should be slower than one-hit search and replace but, as you already saw, there are four variables for four different search patterns working out of one parse cycle.

在给定的假设下,我能想到的最合适的解决方案。

对于MAC用户,如果你没有读评论的话:)

正如@Austin提到的,如果您得到无效的命令代码错误

对于就地替换,BSD sed要求在-i标志之后添加一个文件扩展名,以保存到具有给定扩展名的备份文件中。

Sed -i '.bak'的/find/replace' /file.txt

如果您想跳过备份,可以使用“空字符串”。

Sed -i " 's/find/replace' /file.txt

这都是奥斯汀的功劳

可以使用rpl命令。例如,你想改变整个php项目的域名。

rpl -ivRpd -x'.php' 'old.domain.name' 'new.domain.name' ./path_to_your_project_folder/  

这不是一个明确的bash的原因,但它是一个非常快速和有用的。:)

试试下面的shell命令:

find ./  -type f -name "file*.txt" | xargs sed -i -e 's/abc/xyz/g'

您也可以在bash脚本中使用python。我在这里的一些顶级答案上没有太大的成功,并且发现这个不需要循环就能工作:

#!/bin/bash
python
filetosearch = '/home/ubuntu/ip_table.txt'
texttoreplace = 'tcp443'
texttoinsert = 'udp1194'

s = open(filetosearch).read()
s = s.replace(texttoreplace, texttoinsert)
f = open(filetosearch, 'w')
f.write(s)
f.close()
quit()