Tuesday, August 30, 2011

Search and replace recursively on a directory in Linux

Here is the small bash shell script to make life simple... This script can do a search for string and replace with a new string recursively in a directory.

--------------------------------------------------------------------------------
#!/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 "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
grep -q $1 $f
if [ $? = 0 ];then
cp $f $f.1bak
echo "The string $1 will be replaced with $2 in $f"
sed s/$1/$2/g < $f.1bak > $f
rm $f.1bak
fi
done

else
#print usage informamtion
usage
fi