我需要获取给定目录中的所有 .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/