Search and Replace for multiple files

Here is a quick tip to help doing search and replace in multiple files.    You may need to change to fit your needs.

for file in `ls *.php`
do
sed -e ‘s/Copyright 2008/Copyright 2009/’ “$file” > tmp_file
mv -f tmp_file “$file”
done

What this does is get’s a list of all php files in the current directory, puts them in a loop with a variable called FILE, then does a sed search and replace calling the new file tmp_file and moving the temp file back in place.  If you wanted to do it for all files including in subdirectories, you could substitute:

ls *.php

with:

find ./ -name “*.php”

3 Responses

  1. John Pelster Says:

    I used an almost identical solution a few years back, and discovered one “gotcha”…

    If you are running a php script as a cron job (for example) and you need it to be executable, then unless your umask is set properly, you’re probably going to drop your executable permissions when you redirect the sed output and then mv it back over the original.

    – John

  2. mshields Says:

    You are correct. One way to get around losing the permissions would be to change the “mv” line to

    cat tmp_file > “$file”

  3. Charlie Says:

    Hi Matt,
    I wrote an open source program which allows you to run multiple replacements across multiple files. The link is here: http://www.neptuneweb.com/find_and_replace.html

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.