我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
将当前目录和子目录(不包括.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' {} +
其他回答
我只使用上衣:
find . -name '*.[c|cc|cp|cpp|m|mm|h]' -print0 | xargs -0 tops -verbose replace "verify_noerr(<b args>)" with "__Verify_noErr(<args>)" \
replace "check(<b args>)" with "__Check(<args>)"
对于IBMi上的Qshell(qsh),不是OP标记的bash。
qsh命令的限制:
find没有-print0选项xargs没有-0选项sed没有-i选项
因此,qsh中的解决方案:
PATH='your/path/here'
SEARCH=\'subdomainA.example.com\'
REPLACE=\'subdomainB.example.com\'
for file in $( find ${PATH} -P -type f ); do
TEMP_FILE=${file}.${RANDOM}.temp_file
if [ ! -e ${TEMP_FILE} ]; then
touch -C 819 ${TEMP_FILE}
sed -e 's/'$SEARCH'/'$REPLACE'/g' \
< ${file} > ${TEMP_FILE}
mv ${TEMP_FILE} ${file}
fi
done
注意事项:
解决方案不包括错误处理不是OP标记的Bash
我只是需要这一点,并对现有示例的速度感到不满意。所以我想出了自己的办法:
cd /var/www && ack-grep -l --print0 subdomainA.example.com | xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'
Ack-grep在查找相关文件方面非常有效。这个命令轻而易举地替换了约145000个文件,而其他命令耗时太长,我无法等到它们完成。
这一个与git存储库兼容,而且更简单:
Linux:
git grep -l 'original_text' | xargs sed -i 's/original_text/new_text/g'
Mac:
git grep -l 'original_text' | xargs sed -i '' -e 's/original_text/new_text/g'
(感谢http://blog.jasonmeridth.com/posts/use-git-grep-to-replace-strings-in-files-in-your-git-repository/)
如果您想在不完全破坏SVN存储库的情况下使用此功能,可以通过以下操作告诉“查找”忽略所有隐藏文件:
find . \( ! -regex '.*/\..*' \) -type f -print0 | xargs -0 sed -i 's/subdomainA.example.com/subdomainB.example.com/g'