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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

使用grep和sed的组合

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

其他回答

#!/usr/local/bin/bash -x

find * /home/www -type f | while read files
do

sedtest=$(sed -n '/^/,/$/p' "${files}" | sed -n '/subdomainA/p')

    if [ "${sedtest}" ]
    then
    sed s'/subdomainA/subdomainB/'g "${files}" > "${files}".tmp
    mv "${files}".tmp "${files}"
    fi

done

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

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

或者使用极快的GNU Parallel:

grep -rl oldtext . | parallel sed -i 's/oldtext/newtext/g' {}

如果您可以访问节点,可以执行npm安装-grexreplace,然后

rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*

对我来说,最容易记住的解决方案是https://stackoverflow.com/a/2113224/565525即:

sed -i '' -e 's/subdomainA/subdomainB/g' $(find /home/www/ -type f)

注意:-i“”解决了OSX问题sed:1:“…”:命令代码无效。

注意:如果要处理的文件太多,参数列表会太长。解决方法-使用上述find-exec或xargs解决方案。