-   Linux - Newbie (
-   -   Search and Replace a string1 with string2 in many files (

TroelsSmit 12-16-2004 09:13 AM

Search and Replace a string1 with string2 in many files

I would like to do something like:

$fil foreach( find . -name * ){

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

How do I do this ?


Mik 12-16-2004 09:31 AM

For bash you would do something like

for file in `find . -type f`
sed -i 's/string1/string2/g' $file;

TroelsSmit 12-16-2004 10:08 AM

got this scripts working:

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

(cannot be very fast, but it works)

Mik 12-16-2004 01: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 01:51 PM

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

Thanks again!

Tinkster 12-16-2004 02: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' {} \;


All times are GMT -5. The time now is 06:50 PM.