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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

更简单的方法是在命令行上使用以下命令

find /home/www/ -type f|xargs perl -pi -e 's/subdomainA\.example\.com/subdomainB.example.com/g' 

其他回答

最简单的替换方式(所有文件、目录、递归)

find . -type f -not -path '*/\.*' -exec sed -i 's/foo/bar/g' {} +

注意:有时您可能需要忽略一些隐藏文件,例如.git,您可以使用上面的命令。

如果要包含隐藏文件,请使用,

find . -type f  -exec sed -i 's/foo/bar/g' {} +

在这两种情况下,字符串foo将被替换为新的字符串栏

cd /home/www && find . -type f -print0 |
      xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

一个很好的oneliner作为额外的。使用git grep。

git grep -lz 'subdomainA.example.com' | xargs -0 perl -i'' -pE "s/subdomainA.example.com/subdomainB.example.com/g"

如果您不介意将vim与grep或find工具一起使用,您可以在以下链接中跟进用户Gert给出的答案-->如何在大文件夹层次结构中进行文本替换?。

交易如下:

递归地对要在某个路径中替换的字符串执行grep,并只获取匹配文件的完整路径。(这将是$(grep”字符串“”路径名“-Rl”)。(可选)如果您想对集中目录上的这些文件进行预备份,您也可以使用以下命令:cp-iv$(grep‘string‘‘pathname‘-Rl)‘集中目录路径名‘之后,您可以在vim中按照与给定链接上提供的方案类似的方案随意编辑/替换::bufdo%s#string#replacement#gc | update

我只使用上衣:

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