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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

我只使用上衣:

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>)" 

其他回答

使用grep和sed的组合

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

或者使用极快的GNU Parallel:

grep -rl oldtext . | parallel sed -i 's/oldtext/newtext/g' {}
find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

-print0告诉find打印由空字符分隔的每个结果,而不是新行。如果您的目录中包含名称中带有换行符的文件,这是不太可能的,那么xargs仍然可以使用正确的文件名。

\(-type d-name.git-prenne\)是一个表达式,它完全跳过名为.git的所有目录。如果您使用SVN或有其他要保留的文件夹,则可以轻松展开它,只需匹配更多名称即可。它大致相当于-not-path.git,但效率更高,因为它不检查目录中的每个文件,而是完全跳过它。后面的-o是必需的,因为-prime实际上是如何工作的。

有关更多信息,请参阅man find。

对于任何使用银搜索器(ag)的人

ag SearchString -l0 | xargs -0 sed -i 's/SearchString/Replacement/g'

由于ag默认忽略git/hg/svn文件/文件夹,因此在存储库中运行是安全的。

将当前目录和子目录(不包括.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' {} +