Recursive search and replace?

Ripcord

Senior Lurker
Does anyone know of any way to do a "search and replace" in several files with some command line utility?

Right now I can run "grep -R 'datapattern' *" and FIND a pattern, I'd like to do "findandreplace -R 'original' 'replacement' *" if possible... I have a LOT of files to change some data patterns in...
 
Okay, let me see if I can provide at least 50% of an answer...

Using awk will let you search and replace a pattern inside of a file quite easily. Use a syntax like this:

awk '/oldpattern/ { s/oldpattern/newpattern/ }'

Then if you tie that to the find command to get all the available files, you should be all set. Try this:

find searchdirectory -print -exec awk '/oldpattern/ { s/oldpattern/newpattern/ }' {}\;

Chances are that I messed up the syntax of the -exec switch since I never use it. ;-) Wait for someone else to confirm that it works before you blow away your important files.
 
However, awk will not modify the original file in place because it is a filter. BTW, the same can be done even faster with
sed -e's|oldpattern|newpattern|g' <origfile >newfile
 
Well then you could get MOST of the way there with this:

find / -name * -exec sed -e's|oldpattern|newpattern|g' <{} >{}.new \;

The trouble is, this would not modify the existing files, but create new ones with a .new extension.

How about this: write a short shell script which accepts a filename as an argument, and when run it will do this:

#!/bin/sh
sed -e's|oldpattern|newpattern|g' <$1 >$1.new
rm $1
mv $1.new $1

Save it in your Home directory as 'doReplace.sh'.
Be sure to:
chmod a+x doReplace.sh

Then do this:

find . -name * -exec ~/doReplace.sh {} \;


Seems like it ought to work, eh?
 
Back
Top