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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

我很惊讶我没有看到使用文件globbing的简单答案,我只使用**/package.json扫描/更新package.json文件

这是zsh下macos特有的

cd /home/www
sed -i '' -e 's/subdomainA.example.com/subdomainA.example.com/g' **/*

其他回答

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

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

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

您可以使用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

希望这对你有帮助!!!

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

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

对于IBMi上的Qshell(qsh),不是OP标记的bash。

qsh命令的限制:

find没有-print0选项xargs没有-0选项sed没有-i选项

因此,qsh中的解决方案:

    PATH='your/path/here'
    SEARCH=\'subdomainA.example.com\'
    REPLACE=\'subdomainB.example.com\'

    for file in $( find ${PATH} -P -type f ); do

            TEMP_FILE=${file}.${RANDOM}.temp_file

            if [ ! -e ${TEMP_FILE} ]; then
                    touch -C 819 ${TEMP_FILE}

                    sed -e 's/'$SEARCH'/'$REPLACE'/g' \
                    < ${file} > ${TEMP_FILE}

                    mv ${TEMP_FILE} ${file}
            fi
    done

注意事项:

解决方案不包括错误处理不是OP标记的Bash

根据这篇博文:

find . -type f | xargs perl -pi -e 's/oldtext/newtext/g;'