Skip to content
Nirav MehtaSearch

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…

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:

./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.

#!/bin/sh
grep -rl $2 $1 |
while read filename
do
(
echo $filename
sed "s/$2/$3/g;" $filename \> $filename.xx
mv $filename.xx $filename
)
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!

10 comments

Comments are closed - these are preserved from the original posts.

  1. t3rmin4t0r

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

  2. Nirav

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

  3. Nirav

  4. Leonardo

    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.

  5. ezequiel

    I haven't ever seen a better file than this. It solved me days of work, you are gorgeous.

    I NEVER write comments to posts because I don't have time, but this time I have 4 working-days of free credit that you have just saved me with this file.

    Thanks. ezequiel.

  6. Rookie

    For whole words, update line 7:
    sed "s/\b$2\b/$3/g;" $filename> $filename.xx

  7. Trestini

    sed -i 's/oldText/newText/g' `grep -ril 'oldText' *` works fine for me

  8. Antonio

    A small improvement:
    Change

    mv $filename.xx $filename

    by

    cp $filename.xx $filename
    rm $filename.xx

    and original file permissions will be preserved

  9. Hugo Magalhães

    You can avoid the creation of a temporary file using -i option for sed:

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

    Regards,

  10. Ryan

    I could not get any of these working. But this works great:

    #!/bin/bash
    for filename in `grep -rl $2 $1`
    do
    echo $filename
    sed -i "s#$2#$3#g;" $filename
    done

Esc to closeopen the full search page