LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Search and Replace a string1 with string2 in many files (http://www.linuxquestions.org/questions/linux-newbie-8/search-and-replace-a-string1-with-string2-in-many-files-267010/)

TroelsSmit 12-16-2004 08:13 AM

Search and Replace a string1 with string2 in many files
 
Hi,

I would like to do something like:

#!/bin/tcsh
$fil foreach( find . -name * ){
sed(%s/string1/string2/g)
}


that is,
1. go though a directory structure recursively.
2. replace string1 with string2 in all files

How do I do this ?

THANKS :-)

Mik 12-16-2004 08:31 AM

For bash you would do something like

#!/bin/bash
for file in `find . -type f`
do
sed -i 's/string1/string2/g' $file;
done

TroelsSmit 12-16-2004 09:08 AM

thanks,
got this scripts working:

#!/bin/bash
echo "Version 0"
rm -f tmp
for file in `find . -type f`
do
echo $file
sed 's/asdf/fdsa/g' $file > tmp;
rm -f $file
cat tmp > $file
rm -f tmp
done


(cannot be very fast, but it works)

Mik 12-16-2004 12:09 PM

That does pretty much the same thing. You might want to use the -i option for sed which edits the file directly. Since you aren't doing anything with the tmp file anyways. Saves you a few lines.

TroelsSmit 12-16-2004 12:51 PM

My version of SED doesn't know the "-i" option - thats why I rewrote your script.

Thanks again!

Tinkster 12-16-2004 01:04 PM

Update your sed to 4.x ;}

Besides that, if it wasn't for that deletion you could
even get away with

find -type f -exec sed -i 's/asdf/fdsa/g' {} \;


Cheers,
Tink


All times are GMT -5. The time now is 05:51 AM.