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
While it can be done from the command line, sometimes you just want an easily usable script that provides a bit more useful output. With that in mind, here is a perl solution with friendly output for anyone that runs across this question.
If you are on Unix like platform, you can do it using Perl on the command line; no need to write a script.
TO be on the safer side, you may want to use the command with the backup option.
Perl here is just to modify files... I don't understand why to write it whole in perl if you can do it much simpler like this:
Perhaps the following will be helpful:
A hash of arrays (HoA) is built by
split
ting the|
-delimited DATA lines, where the key is the file name and the value is a reference to an anonymous array whose two elements are for the substitution on the file. Thelocal $^I = '.bak'
notation creates backups of the original files.You may need to adjust the substitution. For example, word boundaries are observed in the substitution by using
\b
ins/\b\Q$replacements{$file}[0]/$replacements{$file}[1]/g;
. You may or may not need (or want) this.I'd suggest trying it on only one 'scratch' file first, to insure you're getting the results you want, before fully implementing it--even though the original files are backed up.
Your script is a good attempt.
It contains a few redundancies:
cp
$f
$TFILE
is useless as well (just write thesed
output to the target file directly)You can construct
$NEW
and the target filename from the value of$f
without the directory path, which you can obtain as follows:In case you really need to do this with perl only, which I don't recommend as there are excellent and simpler answers already posted, here goes:
Please note that doing this with simple find and or shell wildcards is much simpler. But take this as a little tutorial on how to process files with perl anyway.