1833451 Members
2856 Online
110052 Solutions
New Discussion

Re: Search and Replace

 
SOLVED
Go to solution
Leo The Cat
Regular Advisor

Search and Replace

Hi

I want to replace string1 by string2 in some text files.

Actually I'm using a script mixeed with Perl and it works very well. Is there another possibility but without perl ?

...
find *.txt -type f -exec perl -i -pe 's|\string1\E|string2|g' {} \;
...

any idea ?

Regards
Den
4 REPLIES 4
Rita C Workman
Honored Contributor

Re: Search and Replace

Maybe:

Change something in file & have it right back to same filename .

sed "s/old.info/new.info/g" file | tee file


Rgrds,
Rita
James R. Ferguson
Acclaimed Contributor

Re: Search and Replace

Hi Den:

The advantage to Perl is that this snippet performs an "inplace" update of every file found by the 'find' commmand in a very straightforware way.

You could use 'sed' to perform the substitution, but then you would have to redirect the output to a file of a *different* name. Then you have to rename the new output file to be that of the old input file to replace it.

This means that you really need to have a small script like:

#!/usr/bin/sh
sed -e s'|string1|string2|g' ${1} > ${1}.new
mv ${1}.new ${1}

...and do:

# find *.txt -type f -exec /usr/local/bin/mything {} \;

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor
Solution

Re: Search and Replace

Hi (again):

Unfortunately, you cannot do variations like these with 'sed':

# sed -e 's/x/y/g' file | tee file

# sed -e 's/x/y/g' file > file

Your result will be garbage.

Regards!

...JRF...
Leo The Cat
Regular Advisor

Re: Search and Replace

The solution and explaination proposed by JRF is a good.