Searching recursively through the contents a directory.

A bash script to search recursively through the entire current directory looking for the specified text. I’m just posting this because it’s something I use fairly regularly.

#!/bin/bash
lookingFor=$1
target=$2
MINLEN=${#lookingFor}
i=0
for f in `find $target ! -type d`;
do
 if [ $f == $0 ]; then
j=12
 else
line=`grep -i "$lookingFor" $f | sed 's/^[ \t]*//'`
#echo $line
len=${#line}
if [ "$MINLEN" -lt "$len" ]; then
 echo "$f:`grep -n "$lookingFor" $f | cut -f1 -d:`"
 echo "$line"
 echo ""
 i=$(($i+1))
fi
 fi
done

echo $i" files found with: "$lookingFor

Save this file I like to call my ‘search’ and set it to executable;

chmod +x search

To use it just

./search needle haystack

Leave a Reply

Your email address will not be published. Required fields are marked *