Simple Find and Replace Command

posted Feb 12, 2012, 8:49 PM by Sachchida Ojha   [ updated Feb 12, 2012, 8:49 PM ]

#!/bin/bash
# This script will search and replace all regular files for a string
# supplied by the user and replace it with another string.
#

function usage {
echo ""
echo "Search/replace script"
echo " Written by Sachchida ojha"
echo " snojha@dbaref.com"
echo " http://www.dbaref.com"
echo ""

echo "Not enough parameters provided."
echo "Usage: ./$0 searchstring replacestring"
echo "Remember to escape any special characters in the searchstring or the replacestring"
echo ""
}

#check for required parameters
if [ ${#1} -gt 0 ] && [ ${#2} -gt 0 ];
then
for f in `find -type f`;
do
cp $f $f.bak
echo "The string $1 will be replaced with $2 in $f"
sed s/$1/$2/g < $f.bak > $f
rm $f.bak
done
else
#print usage informamtion
usage
fi

Comments