Search and Replace Recursively using sed and grep

I have done this so many times, still I find a new problem doing recursive search and replace each time! Here's one small shell script that puts the issues I had on the Mac doing search and replace on a directory recursively.

Save the file as rpl.sh, chmod it 755, and execute it like:

CODE:
  1. ./rpl.sh folderContainingFiles/ oldText newText

Does the job for me! This could be done in a single line, I got some ideas of using xargs etc, but all that did not work on my Mac (at least). So resorting to this.

CODE:
  1. #!/bin/sh
  2. grep -rl $2 $1 |
  3.  while read filename
  4.  do
  5.  (
  6.   echo $filename
  7.   sed "s/$2/$3/g;" $filename> $filename.xx
  8.   mv $filename.xx $filename
  9.  )
  10.  done

And yes, if you are going to use this, take a little time and do some argument checking before passing them around! Unless you think only a God user like you is going to use it!

 

4 comments ↓

#1 t3rmin4t0r on 12.31.07 at 6:34 am

find containingFolder/ -type f -exec sed -i~ “s/oldText/newText/g” {} \;

#2 Nirav on 01.04.08 at 9:20 am

The exec part here: wouldn’t it fork a new process for every file? Is that a good practice? I thought otherwise!

#3 Nirav on 01.04.08 at 9:20 am

BTW, Manish has a way to do this using Perl - http://mannu.livejournal.com/406783.html.

#4 Leonardo on 06.25.08 at 11:30 pm

for i in `find` ; do sed “s/pattern/replacement/g” “$i” >> “$i.xx”; mv “$i.xx” “$i”; done

I don’t know if this work in mac.

Leave a Comment