Zach Shepherd's WordPress Blog

Just another WordPress weblog

Friday, May 9, 2008

Find-Replace

Well, I wanted to find and replace over an entire directory (and keep a backup of the old files), and I couldn’t find any straightforward way to do it, so I came up with a nifty little bash command to do it using a for loop and sed.

for $file in $(find . -type f);
do
sed 's/FINDME/REPLACEME/g' $file > $file.tmp;
mv $file $file.bak;
mv $file.tmp $file;
done

posted by Zach at 4:54 pm  

3 Comments »

  1. So you can save the two moves by using sed’s -i (in place) option which can also create a backup file for you. And since that whittles it down to a single command, you can then use the -exec option to find instead of a for loop:

    find . -type f -exec sed -i.bak ’s/FINDME/REPLACEME/g’ {} \;

    Btw, in the version you wrote the variable used in the for loop can’t have the $ there when being declared (to bash it’s an invalid identifier). The semicolons also aren’t necessary in any of the places you’ve used them since the expressions are on their own lines. You’ll also get problems with your version if there are spaces in the file names

    Comment by Kyle — May 10, 2008 @ 8:49 am

  2. Thanks! I knew there was a reason I left comments enabled; that looks much easier than what I came up with! I should have read the sed man page a bit more closely; I didn’t see the -i option. As for the $ in the for loop, I apologize; I must have added that when cleaning up the code to post. (The same goes for the semicolons; if you remove the line breaks, you have a ‘one liner’, but it went way off of the page both here and on planet.)

    Comment by Zach — May 10, 2008 @ 9:22 am

  3. there is also a lesser known “rename” command that may be able to do what you are looking for too.

    Comment by Todd Deshane — May 16, 2008 @ 11:11 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress