November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Categories

November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Search and replace recursively on a directory in Linux

Search and replace recursively on a directory in Linux

ere 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
——————————————————————–

1 comment to Search and replace recursively on a directory in Linux

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>