#!/bin/sh 
# This script replaces a string (sed regular expression) by another 
# string in a list of files.
# For each file, say 'filename', the following steps are taken:
# (i) Perform the string replacement and copy the result to 
# 'filename.new'.
# (ii) If 'filename' and 'filename.new' are different then
#      make a copy of 'filename' in 'filename.old' and replace 
#      'filename' with 'filename.new' 
# In other words, the file 'filename' is overwritten only if the 
# string replacement results in a modification.  The original file
# 'filename' is copied to 'filename.old' as a backup.
#
# Shortcomings:
# Add interactive feature, so that the user can confirm replacements. 
#
# Usage:
# strrep old_string new_string list_of_files
#
# Example 1:
# The following example replaces "lib.*" with "lib.IPaddr" in all java
# files in the current directory.  Note that '*' is escaped
# following sed's escaping rules. 
# sed's rules. 
# strrep 'lib.\*' 'lib.IPaddr' *.java
#
# Example 2:
# This example replaces all occurances of
# /home/johnh/BIN/perl5 with /usr/bin/perl5.  Note that the 
# '/' is also be escaped, as shown in the previous example. 
# strrep '\/home\/johnh\/BIN\/perl5' '\/usr\/bin\/perl5' *
# 
#
# Author:         Graham Phillips <graham@isi.edu>
# Date created:   September 1998 
# Last modified:  August    1999
#

OLD_STRING=$1
NEW_STRING=$2
NEW_EXT=.new
BAK_EXT=.old

# should spit out a help message when there are no arguments
shift 2
FILES=$*

for file in $FILES
do
	NEW_FILE=$file$NEW_EXT 
        eval "sed -e '1,\$s/$OLD_STRING/$NEW_STRING/g' $file > $NEW_FILE"
	if [ "`diff $NEW_FILE $file`" != "" ] ; then  
		echo "replacing \"$OLD_STRING\" with \"$NEW_STRING\" in $file"
		mod=`ls -l $file | sed 's/.\(...\)\(...\)\(...\).*/u=\1,g=\2,o=\3/' | sed 's/-//g'`
		mv $file $file$BAK_EXT
        	mv $NEW_FILE $file
		chmod $mod $file
	fi
	rm -f $NEW_FILE
done

