#!/bin/ksh
############################################################################
#
# Replace one string with another in  files and subdirs
#
#
# This version makes no
# backups, so don't use it on live stuff.
############################################################################

############################################################################
#  Setup variables
#
PathToStartFrom=$1
StringToSearchFor=$2
StringToReplaceWith=$3
TemporaryFile=/tmp/CreatedByReplaceAll.sh

############################################################################
# Validate input
#
if [ ${StringToSearchFor}a = a ] || [ ${StringToReplaceWith}a = a ] || [ ${PathToStartFrom}a = a ] ; then
        echo "Usage Path Search Replace"
        echo "Where \"Path\"=Path to Search, \"Search\"=String to search for and \"Replace\"=String to replace with"
        exit 1
fi

############################################################################
# Create a list of all files to be replaced and show it with the option to abort
#
if [ -d $PathToStartFrom ] ; then
        cd $PathToStartFrom
else
        echo "Directory $PathToStartFrom does not exist"
        exit 1
fi
#echo "searching $PathToStartFrom ..."
find . -type f -name '*' -exec grep -l $StringToSearchFor {} \; > /tmp/filestoupdate.txt

# Put a backslash "\" in front of all frontslashes "/" to get it through sed
#
ModiStringToSearchFor=`echo $StringToSearchFor | sed 's/\//\\\\\//g'`
ModiStringToReplaceWith=`echo $StringToReplaceWith | sed 's/\//\\\\\//g'`

# Loop through the list and replace the text
#
exec 3< /tmp/filestoupdate.txt
while read -u3 FileName; do
        Command="s/${ModiStringToSearchFor}/${ModiStringToReplaceWith}/g"
        sed $Command $FileName > $TemporaryFile
        cat $TemporaryFile >  $FileName
done

