我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
要替换git存储库中的所有事件,可以使用:
git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'
查看本地git repo中的列表文件?获取列出存储库中所有文件的其他选项。-z选项告诉git用零字节分隔文件名,这确保xargs(使用选项-0)可以分隔文件名(即使它们包含空格或其他内容)。
其他回答
#!/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
注意:不要在包含git repo的文件夹上运行此命令-对.git的更改可能会损坏git索引。
find /home/www/ -type f -exec \
sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
与这里的其他答案相比,这比大多数答案都简单,并且使用sed而不是perl,这就是最初的问题所要求的。
对我来说,最容易记住的解决方案是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解决方案。
我很惊讶我没有看到使用文件globbing的简单答案,我只使用**/package.json扫描/更新package.json文件
这是zsh下macos特有的
cd /home/www
sed -i '' -e 's/subdomainA.example.com/subdomainA.example.com/g' **/*
将当前目录和子目录(不包括.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' {} +