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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With