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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

对我来说最简单的方法是

grep -rl oldtext . | xargs sed -i 's/oldtext/newtext/g'

其他回答

试试看:

sed -i 's/subdomainA/subdomainB/g' `grep -ril 'subdomainA' *`

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

您可以使用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

希望这对你有帮助!!!

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

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

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

将当前目录和子目录(不包括.git/)中所有.c和.h文件的所有匹配string_1的内容替换为string_2。

这适用于Mac:

find . -type f -path "*.git*" -prune -o -name '*\.[ch]' -exec \
sed -i '' -e 's/'$1'/'$2'/g' {} +

这应该可以在Linux上运行(尚未测试):

find . -type f -path "*.git*" -prune -o -name '*\.[ch]' -exec \
sed -i 's/string_1/string_2/g' {} +