我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
只是为了避免改变
NearlysubdomainA.example.com附近子域例如comp.other
但仍然
子域A.example.com.IIt.good
(在域名根背后的想法可能不太好)
find /home/www/ -type f -exec sed -i 's/\bsubdomainA\.example\.com\b/\1subdomainB.example.com\2/g' {} \;
其他回答
如果您不介意将vim与grep或find工具一起使用,您可以在以下链接中跟进用户Gert给出的答案-->如何在大文件夹层次结构中进行文本替换?。
交易如下:
递归地对要在某个路径中替换的字符串执行grep,并只获取匹配文件的完整路径。(这将是$(grep”字符串“”路径名“-Rl”)。(可选)如果您想对集中目录上的这些文件进行预备份,您也可以使用以下命令:cp-iv$(grep‘string‘‘pathname‘-Rl)‘集中目录路径名‘之后,您可以在vim中按照与给定链接上提供的方案类似的方案随意编辑/替换::bufdo%s#string#replacement#gc | update
如果您可以访问节点,可以执行npm安装-grexreplace,然后
rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*
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。
这一个与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/)
您可以使用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
希望这对你有帮助!!!