[英]Shell script to find and replace a string
Hello I have a colleague of mine who is a procedural code developer and has same smtp server name sitting in 120 different files, now I have to change them to something else. 您好,我的一位同事是程序代码开发人员,并且在120个不同文件中具有相同的smtp服务器名称,现在我必须将其更改为其他名称。 But doing that one by one would be impossible.
但是一个接一个地做是不可能的。 I am using "grep" to recursively search for a string in all the files sitting in that directory.
我正在使用“ grep”在该目录中的所有文件中递归搜索字符串。 But I am not sure if grep can edit the file and replace it with the new string.
但是我不确定grep是否可以编辑文件并将其替换为新字符串。
Thanks 谢谢
Shouldn't this be on serverfault? 这不应该在serverfault上吗?
Anyway, you should be looking at a combination of find
and sed
. 无论如何,您应该将
find
和sed
结合使用。
Possibly something like: 可能是这样的:
find . -iname "<filepattern>" -exec sed -e "s/<regex to look for>/<replacement>/g" -i {} \;
Use sed
. 使用
sed
。
grep -rl smtp1.example.com . | xargs sed -i 's/smtp1.example.com/smtp2.example.com/g'
which means find all files containing smtp1.example.com
; 这意味着找到所有包含
smtp1.example.com
文件; output their names; 输出他们的名字; pass each filename to the
sed
command, which does a search-and-replace on each file. 将每个文件名传递给
sed
命令,该命令对每个文件进行搜索和替换。
grep
will only list files that actually contain the text; grep
将仅列出实际包含文本的文件; this minimises the number of files for which sed
is invoked. 这样可以最大程度地减少调用
sed
的文件数量。 (Using find -type f
results in sed
being invoked on any file.) (使用
find -type f
导致在任何文件上调用sed
。)
find /directory -type f -exec sed -i 's/oldname/newname/g' {} +
Searches recursively through /directory
and uses sed
to do a search and replace. 递归搜索
/directory
并使用sed
进行搜索和替换。 The {}
is replaced by the file names that are found. {}
替换为找到的文件名。
也许是这样的吗?
find /path/to/start/from/ -type f | xargs perl -pi -e 's/textToFind/TextToReplace/g'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.