Replacing a word in all files in a directory

Here is a common problem. A directory has many files. In each of these files we want to replace all occurrences of a string with another string. On top of that we want to only do this for regular files.

#!/bin/sh
# sed/changeword

prog=`basename $0`
case $# in
0|1) echo 'Usage:' $prog '<old string> <new string>'; exit 1;;
esac

old=$1
new=$2
for f in *
do
        if test "$f" != "$prog"
        then
            if test -f "$f"
            then
                sed "s/$old/$new/g" $f > $f.new
                mv $f $f.orig
                mv $f.new $f
                echo $f done
            fi
        fi
done

First the case statement checks for proper arguments to the script and displays a help message if it doesn't have the right number of command line arguments.

The for loop selects all files in the current directory. The first if statement makes sure that we do not select the script itself! The second if tests to check that the selected file is a regular file. Finally we use sed to do the global search and replace in each selected file. The script saves a copy of each original file (in case of a problem).