General

Change all the occurences of a text in multiple files

 
SOLVED
Go to solution
Grep and replace
Occasional Contributor

Change all the occurences of a text in multiple files

How do i replace a occurence of pattern with new pattern in multiple files in a directory ?

e.g I want to change the following in all the files.
A=X.Y.Z.com to

A=A.B.C.com
6 REPLIES 6
Paul Sperry
Honored Contributor
Solution

Re: Change all the occurences of a text in multiple files

cd /dir
find . -type f -exec perl -pi -e 's/A=X.Y.Z.com/A=A.B.C.com/g' {} \;
Patrick Wallek
Honored Contributor

Re: Change all the occurences of a text in multiple files

Something like might work as well. You just have to supply the list of files.

for i in test test1 test2
do
mv ${i} ${i}.orig
sed s/A\=X.Y.Z.com/A=A.B.C.com/g ${i}.orig > ${i}
rm -f ${i}.orig
done
Yang Qin_1
Honored Contributor

Re: Change all the occurences of a text in multiple files

Or keep a backup with perl one line command:
find . -type f -exec perl -pi'.bak' -e 's/A=X.Y.Z.com/A=A.B.C.com/g' {} \;

Yang
James R. Ferguson
Acclaimed Contributor

Re: Change all the occurences of a text in multiple files

Hi:

A bit faster way avoids the '-exec' for every file found and thus eliminates spawning a separate process (Perl) for each file found:

# FILES=`find /path -xdev -type f`; perl -pi.old -e 's/A=X\.Y\.Z\.com/A=A.B.C.com/g' ${FILES}

...This example finds a *files* in '/path' and performs your replacement therein, in-place. A backup copy of each file is retained with the ".old" extension. Note that a "." is a metacharacter so it is escaped to match only "." character.

Regards!

...JRF...
Paul Sperry
Honored Contributor

Re: Change all the occurences of a text in multiple files

By the way, I see you are new here.
Welcome to the forums !!
Peter Nikitka
Honored Contributor

Re: Change all the occurences of a text in multiple files

Hi,

as you see from the previous answers, there is more than one way to to it. In Patrick's solution I would introduce a small additional check, if the write operation really succeded:

for i in test test1 test2
do
mv ${i} ${i}.orig
if sed s/A\=X.Y.Z.com/A=A.B.C.com/g ${i}.orig > ${i}
then rm -f ${i}.orig
fi
done

Another possibility without (visible) temporary files is to generate an ed/ex program:
find . -type f | xargs fgrep -l A=X.Y.Z.com |
while read fnam
do
print e $fnam
print "g/A=X\.Y\.Z\.com/s//A=A.B.C.com/g"
print w
done | ex -

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"