How-to Find & Replace a string in all files within a directory
February 8, 2013 Leave a comment
I run into this several times. I’d like to share how I solve it with shell and perl. Here are the steps:
Step 1. Get a list
for f in `find . -type f` do r=`grep SOURCE_STRING $f` if [ "alex${r}" != "alex" ] ; then echo $f >> update.lst fi done;
Step 2. Check the list
wc update.lst cat update.lst for f in `cat update.lst` do r=`grep SOURCE_STRING $f` echo $f echo $r done;
Step 3. Update files
for f in `cat update.lst` do echo $f perl -i -pe 's/SOURCE_STRING/TARGET_STRING/g' $f done;
Step 4. Check it again run Step 2 again