Monday, July 20, 2009

linux shell script for find and replace strings in a directory

This is a shell script used to find and replace a string with another.This can be directly executed on shell.




#check for required parameters
if [ ${#1} -gt 0 ] && [ ${#2} -gt 0 ];
then
for f in `find -type f`;
do
if grep -q $1 $f;
then
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
fi
done

else
#print usage informamtion
echo usage incorrect.try findscript string1 string2
echo special characters forwarded with slash

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails