Perl:在多个文本文件中查找和替换特定字符串 [英] Perl: Find and replace specific string in multiple text file

查看:46
本文介绍了Perl:在多个文本文件中查找和替换特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to get all the .config file in a given directory and in each of these file I need to search for a specific string and replace with another based on the file.

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

For e.g if I have 3 file in the given directory:

 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 中做到这一点?

Please let me know how this can be done in Perl?

以下是我在 shell 脚本中尝试的代码:

Below is the code that I tried in shell scripting:

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 来完成;无需编写脚本.

If you are on Unix like platform, you can do it using Perl on the command line; no need to write a script.

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

为了更安全,您可能希望使用带有备份选项的命令.

TO be on the safer side, you may want to use the command with the backup option.

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

这篇关于Perl:在多个文本文件中查找和替换特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆