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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

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

交易如下:

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

其他回答

要减少要递归遍历的文件,可以对字符串实例进行grep:

grep -rl <oldstring> /path/to/folder | xargs sed -i s^<oldstring>^<newstring>^g

如果运行man grep,您会注意到,如果您想省略对.git目录的搜索,还可以定义一个--exlude dir=“*.git”标志,从而避免了其他人礼貌地指出的git索引问题。

引导您:

grep -rl --exclude-dir="*.git" <oldstring> /path/to/folder | xargs sed -i s^<oldstring>^<newstring>^g

要替换git存储库中的所有事件,可以使用:

git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

查看本地git repo中的列表文件?获取列出存储库中所有文件的其他选项。-z选项告诉git用零字节分隔文件名,这确保xargs(使用选项-0)可以分隔文件名(即使它们包含空格或其他内容)。

我只使用上衣:

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 . -type f -not -path '*/\.*' -exec sed -i 's/foo/bar/g' {} +

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

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

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

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

您可以使用awk解决如下问题,

for file in `find /home/www -type f`
do
   awk '{gsub(/subdomainA.example.com/,"subdomainB.example.com"); print $0;}' $file > ./tempFile && mv ./tempFile $file;
done

希望这对你有帮助!!!