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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

cd /home/www && find . -type f -print0 |
      xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

其他回答

这是一个比大多数版本更通用的版本;例如,它不需要查找(而是使用du)。它确实需要xargs,只有在Plan9的某些版本(如9front)中才能找到xargs。

 du -a | awk -F' '  '{ print $2 }' | xargs sed -i -e 's/subdomainA\.example\.com/subdomainB.example.com/g'

如果要添加文件扩展名等筛选器,请使用grep:

 du -a | grep "\.scala$" | awk -F' '  '{ print $2 }' | xargs sed -i -e 's/subdomainA\.example\.com/subdomainB.example.com/g'

您可以使用awk解决如下问题,

for file in `find /home/www -type f`
do
   awk '{gsub(/subdomainA.example.com/,"subdomainB.example.com"); print $0;}' $file > ./tempFile && mv ./tempFile $file;
done

希望这对你有帮助!!!

对我来说,最容易记住的解决方案是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解决方案。

根据这篇博文:

find . -type f | xargs perl -pi -e 's/oldtext/newtext/g;'

使用grep和sed的组合

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