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

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' {} +

其他回答

有点陈旧,但这在OS X上有效。

有几个诡计:

•仅编辑当前目录下扩展名为.sls的文件

• . 必须转义,以确保sed不会将它们求值为“任何字符”

•,用作sed分隔符,而不是通常的分隔符/

还要注意,这是为了编辑Jinja模板以在导入路径中传递变量(但这是离题的)。

首先,验证sed命令是否符合您的要求(这只会将更改打印到stdout,不会更改文件):

for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done

准备好进行更改后,根据需要编辑sed命令:

for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed -i '' 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done

请注意sed命令中的-i“”,我不想创建原始文件的备份(如OS X上使用sed进行的就地编辑或本页中Robert Lujo的评论所述)。

快乐的色丁们!

如果您可以访问节点,可以执行npm安装-grexreplace,然后

rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*
perl -p -i -e 's/oldthing/new_thingy/g' `grep -ril oldthing *`

我只使用上衣:

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>)" 
find /home/www/ -type f -exec perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +

find/home/www/-type f将列出/home/ww/(及其子目录)中的所有文件。“-exec”标志告诉find对找到的每个文件运行以下命令。

perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +

是在文件上运行的命令(一次运行多个)。{}被文件名替换。告诉find为多个文件名构建一个命令。

根据查找手册页:“命令行的构建方式与xargs构建其命令行。"

因此,不使用xargs-0或-print0就可以实现目标(并处理包含空格的文件名)。