regex - Perl:在多个文本文件中查找和替换特定字符串

标签 regex perl shell replace

我需要获取给定目录中的所有 .config 文件,并且在这些文件中的每一个中,我需要搜索特定字符串并根据文件替换为另一个。

例如,如果我在给定目录中有 3 个文件:

 for  my_foo.config - string to search "fooCommon >" replace with "~ /fooCommon[\/ >"
 for  my_bar.config - string to search "barCommon >" replace with "~ /barCommon[\/ >"
 for  my_file.config - string to search "someCommon >" replace with "~ /someCommon[\/ >"

请让我知道如何在 Perl 中做到这一点?

下面是我在 shell 脚本中尝试的代码:
OLD="\/fooCommon >"
NEW="~ \"\/fooCommon[^\/]*\" >"
DPATH="/myhome/aru/conf/host*.conf"
BPATH="/myhome/aru/conf/bakup"
TFILE="/myhome/aru/out.tmp.$$"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
   /bin/cp -f $f $BPATH
   echo sed \"s\/$OLD\/$NEW\/g\"
   sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f"
  else
   echo "Error: Cannot read $f"

fi
done
/bin/rm $TFILE

最佳答案

如果你在类 Unix 平台上,你可以在命令行上使用 Perl 来完成;无需编写脚本。

perl -i -p -e 's/old/new/g;' *.config

为了更安全,您可能希望使用带有备份选项的命令。
perl -i.bak  -p -e 's/old/new/g;' *.config

关于regex - Perl:在多个文本文件中查找和替换特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995368/

相关文章:

mysql - 搜索查询的正则表达式,如 : word1 * (word2 -word3 -word4) * word5

javascript - javascript字符串拆分中的正则表达式,浏览器兼容性问题

perl - 只能 'perl6'解析Perl 6吗?

perl - 如何使用 Perl 构建家谱?

python - 将答案传递给 popen.subprocess

linux - ASN 查找别名不起作用

javascript - 将字符串匹配要求转换为正则表达式

MySQL - 查找围绕搜索关键字的单词

perl - 将空行插入 Excel 文档

macos - 在 OS X 中使用 find 来识别正确的权限