Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Find and replace specific string in multiple text file

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.

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[\/ >"

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

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
like image 286
user2589079 Avatar asked Nov 15 '13 07:11

user2589079


1 Answers

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
like image 133
Pankaj Vaidya Avatar answered Sep 20 '22 21:09

Pankaj Vaidya