Languages and Scripting

search n r eplace in all files

 
SOLVED
Go to solution
zxcv
Super Advisor

search n r eplace in all files

Hi guys ,

 

i would like to search for a patern in all subdirectories and then replace the same with another name..

 

say grep "hello" in /home/test  to be replaced with "world" in all the files under /home/test  

8 REPLIES 8
zxcv
Super Advisor

Re: search n r eplace in all files

Hi guys got it thnxx

find ./ -type f -exec sed -i ‘s/string1/string2/’ {} \;
Dennis Handly
Acclaimed Contributor

Re: search & replace in all files

>find ./ -type f -exec sed -i ‘s/string1/string2/’ {} \;

 

HP-UX's sed doesn't have -i.

Also your sed replacement will do substrings.

And if the file doesn't have string1, do you really want to change the modification time?

James R. Ferguson
Acclaimed Contributor
Solution

Re: search & replace in all files


@Dennis Handly wrote:

>find ./ -type f -exec sed -i ‘s/string1/string2/’ {} \;

 

HP-UX's sed doesn't have -i.

Also your sed replacement will do substrings.

And if the file doesn't have string1, do you really want to change the modification time?


Hi:

 

As noted, HP-UX 'sed' lacks the GNU extension for in-place editing.  Perl doesn't and it's available on virtually every HP-UX platform.  Perl's regular expressions can easily address matching substrings or not, too.  As for not updating files without matches, this one-liner would need to be enhanced slightly.  All said:

 

# find . -type f -exec perl -pi.old -e  ‘s/\bstring1\b/string2/’ {} +

 

This will process multiple files for every Perl process forked.  Files will be updated in-place with a backup before modification as "*.old".  The addition of the '\b' (boundry) surrounding the string to be matched tightens the criteria for replacement.

 

Regards!

 

...JRF...

zxcv
Super Advisor

Re: search & replace in all files

hi Guys ,

I went  ahead with the perl option given by James.

It worked like a charm....for me modification time was not imp..just the replacement was.

 

Thanks .

zxcv
Super Advisor

Re: search & replace in all files

Thanks dennis for the -i option...info
Dennis Handly
Acclaimed Contributor

Re: search & replace in all files

>Thanks Dennis for the -i option info

 

Note: GNU sed has that -i.

James R. Ferguson
Acclaimed Contributor

Re: search & replace in all files


@Dennis Handly wrote:

>Thanks Dennis for the -i option info

 

Note: GNU sed has that -i.


Dennis, that's what I noted in my original response :-) You usually read better ;-)

 

Regards!

 

...JRF...

Dennis Handly
Acclaimed Contributor

Re: search & replace in all files

>that's what I noted in my original response

 

I guess I read that as Linux, rather than gnu that you could install on your HP-UX system.