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

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

其他回答

试试看:

sed -i 's/subdomainA/subdomainB/g' `grep -ril 'subdomainA' *`

使用grep和sed的组合

for pp in $(grep -Rl looking_for_string)
do
    sed -i 's/looking_for_string/something_other/g' "${pp}"
done

要更改多个文件(并将备份保存为*.bak):

perl -p -i -e "s/\|/x/g" *

将获取目录中的所有文件并用x替换|称为“Perl馅饼”(简单如馅饼)

如果您需要排除目录(--exclude-dir=..folder),并且文件名可能带有空格(通过对grep-Z和xargs-0使用0Byte来解决),这是一种直接的方法

grep -rlZ oldtext . --exclude-dir=.folder | xargs -0 sed -i 's/oldtext/newtext/g'

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

rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*