Operating System - HP-UX
1752678 Members
5966 Online
108789 Solutions
New Discussion

Search n replace recursively

 
coollllllllllll
Regular Advisor

Search n replace recursively

Hi ,

 

/test  with /home/test123

need to replace only /test  by /work  .

 

Only "/test" , it must not leave test123 as it is .

How do i search and replace recursively ?? for many files 

 

 

 

 P.S.This thread has been moved from HP-UX >System Administration to HP-UX > languages-HP Forums Moderator

11 REPLIES 11
Dennis Handly
Acclaimed Contributor

Re: Search and replace recursively

You could use "find ... -exec magic-script {} +, where magic-script is a sed or perl script that will change the string.

sed -e 's:/test:/work:' file > file.new

 

>Only "/test", it must not leave test123 as it is.

 

Did you really mean "not" above?  My code will replace only the first "/test" by "/work" but also "/teststuff".

coollllllllllll
Regular Advisor

Re: Search and replace recursively

Oops my mistake.

I meant it must leave test123 as it is.

It must replace /test with /work only in all recursive sub-directory .

 

 

 

Dennis Handly
Acclaimed Contributor

Re: Search and replace recursively

>Oops my mistake.

 

(You can use Post Options > Edit Reply to correct it.)

 

If you only want to change /test, is it always followed by a space?  What are all possible delimiters?

Or is it anything that's NOT [A-Z_a-z0-9]?

 

sed -e 's:/test\([^A-Z_a-z0-9]\):/work\1:' file > file.new

coollllllllllll
Regular Advisor

Re: Search and replace recursively

Hi ,

 

Its only /test  always followd by nothing.

 

its a mountpint replacemnt taken from different server.

 

/test to replaced with /work only  ....many files.

/test123 not to be touched

 

want to do it using perl

 

 

Dennis Handly
Acclaimed Contributor

Re: Search and replace recursively

>Its only /test  always followed by nothing.

 

sed -e 's:/test$:/work:' file > file.new

coollllllllllll
Regular Advisor

Re: Search and replace recursively

Hi Dennis ,

 

How can i achieve this for all subdirectory .

In short a one liner sed or perl would be preferable.

 

 

 

coollllllllllll
Regular Advisor

Re: Search and replace recursively

Also for me this ones working fine ;

 

sed -e 's:/test\([^A-Z_a-z0-9]\):/work\1:' file > file.new

 

 

Dennis Handly
Acclaimed Contributor

Re: Search and replace recursively

>How can I achieve this for all subdirectory?

 

You would take the above find command and create magic-script:

 

#!/usr/bin/ksh

# Replaces /test by /work in all files on the command line

for file in $*; do

   sed -e 's:/test\([^A-Z_a-z0-9]\):/work\1:' $file > $file.new

   if [ $? -eq 0 ]; then

      mv $file.new $file

   fi

done

 

You can probably do it easier in one step in perl.

coollllllllllll
Regular Advisor

Re: Search and replace recursively

Hi ,

 

Can u help me with perl.