use*_*079 11 regex shell perl 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[\/ >"
Run Code Online (Sandbox Code Playgroud)
请告诉我如何在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
Run Code Online (Sandbox Code Playgroud)
小智 26
如果您使用的是Unix平台,可以在命令行上使用Perl来完成; 无需编写脚本.
perl -i -p -e 's/old/new/g;' *.config
Run Code Online (Sandbox Code Playgroud)
为了更安全,您可能希望使用带备份选项的命令.
perl -i.bak -p -e 's/old/new/g;' *.config
Run Code Online (Sandbox Code Playgroud)
小智 10
这里的Perl只是修改文件...我不明白为什么要在perl中编写它,如果你能做到这么简单:
find . -maxdepth 1 -type f -name '*.conf' | \
xargs perl -i.bak -pe 's/localhost/example.com/;'
Run Code Online (Sandbox Code Playgroud)