我如何查找并替换每次出现的:

subdomainA.example.com

具有

subdomainB.example.com

递归地在/home/www/目录树下的每个文本文件中?


当前回答

grep-lr'submainA.example.com'|读取文件时;do sed-i“s/submainA.example.com/submainB.example.com/g”“$file”;完成

我想大多数人都不知道他们可以将某些内容导入“while read file”,这样可以避免那些讨厌的-print0参数,同时在文件名中预设空格。

在sed之前进一步添加一个echo,可以让您在实际执行之前查看哪些文件将发生更改。

其他回答

使用grep和sed的组合

for pp in $(grep -Rl looking_for_string)
do
    sed -i 's/looking_for_string/something_other/g' "${pp}"
done

要替换git存储库中的所有事件,可以使用:

git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

查看本地git repo中的列表文件?获取列出存储库中所有文件的其他选项。-z选项告诉git用零字节分隔文件名,这确保xargs(使用选项-0)可以分隔文件名(即使它们包含空格或其他内容)。

对于任何使用银搜索器(ag)的人

ag SearchString -l0 | xargs -0 sed -i 's/SearchString/Replacement/g'

由于ag默认忽略git/hg/svn文件/文件夹,因此在存储库中运行是安全的。

一个很好的oneliner作为额外的。使用git grep。

git grep -lz 'subdomainA.example.com' | xargs -0 perl -i'' -pE "s/subdomainA.example.com/subdomainB.example.com/g"

如果您想在不完全破坏SVN存储库的情况下使用此功能,可以通过以下操作告诉“查找”忽略所有隐藏文件:

find . \( ! -regex '.*/\..*' \) -type f -print0 | xargs -0 sed -i 's/subdomainA.example.com/subdomainB.example.com/g'