我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
#!/usr/local/bin/bash -x
find * /home/www -type f | while read files
do
sedtest=$(sed -n '/^/,/$/p' "${files}" | sed -n '/subdomainA/p')
if [ "${sedtest}" ]
then
sed s'/subdomainA/subdomainB/'g "${files}" > "${files}".tmp
mv "${files}".tmp "${files}"
fi
done
其他回答
cd /home/www && find . -type f -print0 |
xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'
注意:不要在包含git repo的文件夹上运行此命令-对.git的更改可能会损坏git索引。
find /home/www/ -type f -exec \
sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
与这里的其他答案相比,这比大多数答案都简单,并且使用sed而不是perl,这就是最初的问题所要求的。
如果您可以访问节点,可以执行npm安装-grexreplace,然后
rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*
使用grep和sed的组合
for pp in $(grep -Rl looking_for_string)
do
sed -i 's/looking_for_string/something_other/g' "${pp}"
done
如果您不介意将vim与grep或find工具一起使用,您可以在以下链接中跟进用户Gert给出的答案-->如何在大文件夹层次结构中进行文本替换?。
交易如下:
递归地对要在某个路径中替换的字符串执行grep,并只获取匹配文件的完整路径。(这将是$(grep”字符串“”路径名“-Rl”)。(可选)如果您想对集中目录上的这些文件进行预备份,您也可以使用以下命令:cp-iv$(grep‘string‘‘pathname‘-Rl)‘集中目录路径名‘之后,您可以在vim中按照与给定链接上提供的方案类似的方案随意编辑/替换::bufdo%s#string#replacement#gc | update