• Home
  • LinuxBash
  • Searching for a string within all subdirectories under the current directory

Searching for a string within all subdirectories under the current directory

I use my own script, which even allows you to set the number of lines above and below the search parameter, to be displayed, colorizes it and pipes it to less, maintaining its color.

 

#!/bin/bash
echo
echo "Recursive Search Utility by Droidzone"
echo " Created on Oct 31 2011"
echo
echo "Format:"
echo ' search [string_to_search_for] [linesbefore] [linesafter]'
echo
export kpath=$(pwd)
echo "Searching all files and folder below:"
echo -e 'E[37;44m'"33[1m$kpath33[0m"
echo

if [ ! "$2" = "" ] && [ ! "$3" = "" ]
then
grep -R -i -n -A $3 -B $2 "$1" * --color=always|less -R
elif [ ! "$2" = "" ] && [ "$3" = "" ]
then
grep -R -i -n -A $2 -B $2 "$1" * --color=always|less -R
else
grep -R -i -n -A 2 -B 2 "$1" * --color=always|less -R
fi

# Grep format:
# grep [-options] ["what to search"] [where_to_search]
# Search recursively (R)
# Case (I)nsensitive
# (W)ords -Search full words
# -n put line (n)umber
# -v in(v)ert
# -A [num] Show [num] number of lines after
# -B [num] Show [num] number of lines before
# Example 1. Beginning of line ( ^ ) grep "^Nov 10" messages.1
# Example 2. End of the line ( $) grep "terminating.$" messages
# Example 3. Count of empty lines ( ^$ ) grep -c "^$" messages anaconda.log
#Example 4. Single Character (.) grep ".ello" input
# In case if you want to search for a word which has only 4 character you can give grep -w “….” where single dot represents any single character.
# Example 5. Zero or more occurrence (*) of the previous character. For example, the pattern ’1*’ matches zero or more ’1′.
# grep "kernel: *." * matches space
#Example 6. One or more occurrence (+) grep "hi +hello" input
# Example 7. Zero or one occurrence (?) grep "hi ?hello" input
# Example 8.Escaping the special character () If you want to search for special characters (for example: * , dot) in the content you have to escape the special character in the regular expression.
# grep "127.0.0.1" /var/log/messages.4
#Example 9. Character Class ([0-9])[/code]