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

subdomainA.example.com

具有

subdomainB.example.com

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


当前回答

要更改多个文件(并将备份保存为*.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

希望这对你有帮助!!!

cd /home/www && find . -type f -print0 |
      xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

只是为了避免改变

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' {} \;
#!/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

有点陈旧,但这在OS X上有效。

有几个诡计:

•仅编辑当前目录下扩展名为.sls的文件

• . 必须转义,以确保sed不会将它们求值为“任何字符”

•,用作sed分隔符,而不是通常的分隔符/

还要注意,这是为了编辑Jinja模板以在导入路径中传递变量(但这是离题的)。

首先,验证sed命令是否符合您的要求(这只会将更改打印到stdout,不会更改文件):

for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done

准备好进行更改后,根据需要编辑sed命令:

for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed -i '' 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done

请注意sed命令中的-i“”,我不想创建原始文件的备份(如OS X上使用sed进行的就地编辑或本页中Robert Lujo的评论所述)。

快乐的色丁们!