1833788 Members
2663 Online
110063 Solutions
New Discussion

Query

 
SOLVED
Go to solution
Hunki
Super Advisor

Query

I have about 25 files in which I need to convert the string /var/log/test to /var/log/prod ...

find . -name "*.*"|xargs grep "/var/log/test"

Can I make a change thru command line instead of going into each and every file . I am looking for an exact answer.

thanks,
hunki
5 REPLIES 5
Michal Toth
Regular Advisor

Re: Query

yeah, for example it's possible to feed vi with commands from file
James R. Ferguson
Acclaimed Contributor
Solution

Re: Query

Hi:

Use Perl and you can make your updates inplace while creating a backup copy of the original files:

# perl -pi.old -e 's%/var/log/test\b%/var/log/prod%g' file1 file2 file3 ...

This will replace the string "/var/log/test" with "/var/log/prod" in every file passed as an argument. For each file (argument) the original file will be preserved as "*.old".

Regards!

...JRF...
TwoProc
Honored Contributor

Re: Query

this is untested - but should get you close
.....

for i in `find . -type f \
| xargs -i grep -l "\/var\/log\/test" {} `
do
echo ------ fixing file $i -------
cat $i | sed "s/\/var\/log\/test/\/var\/log\/prod/" > $i.new
# Uncomment the following lines to remove
# to remove the .new file if you are
# comfortable with how this thing works,
# and have seen it run sucessfully for a
# while, otherwise it probably does no harm
# to leave it - providing there are no
# security or space issues in leaving the
# these files in place.
# rm $i.new
done

If you need to actually have the new file replace the old one (instead of just having a new file with the ".new" extension on it).

for i in `find . -type f \
| xargs -i grep -l "\/var\/log\/test" {} `
do
echo ------ fixing file $i -------
cat $i | sed "s/\/var\/log\/test/\/var\/log\/prod/" > $i.new
cp $i $i.old.keep.bak
cp $i.new $i
# Uncomment the following lines to remove
# to remove the .new file and the backup file
# if you are comfortable with how this thing
# works, and have seen it run sucessfully for
# a while, otherwise it probably does no harm
# to leave it - providing there are no
# security or space issues in leaving the
# these files in place.
# rm $i.new
# rm $i.old.keep.bak
done
We are the people our parents warned us about --Jimmy Buffett
Hein van den Heuvel
Honored Contributor

Re: Query

Somethign like this perl script is most optimal... but too much work.


use strict;
use warnings;
while () {
my $count = 0;
my $file = $_;
my @lines;
open (OLD, "<$file");
while () {
$count += s%/var/log/test\b%/var/log/prod%g;
push @lines, $_;
}
close OLD;
if ($count) {
$_ = $file;
s/\..*?$/.old/;
rename $file, $_;
open (NEW, ">$file");
print NEW @lines;
close NEW;
}
}
Hunki
Super Advisor

Re: Query

Thanks to All specially JRF.