How-to Find & Replace a string in all files within a directory

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

Advertisements

About Alex Zeng
I would be very happy if this blog can help you. I appreciate every honest comments. Please forgive me if I'm too busy to reply your comments in time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: