Grep recursive search

For searching through files I always end up using grep with a number of options. Because I don’t like typing the grep command and all its options over and over, I decided to create a bash file.

Script

!/bin/bash
text=$1
if [ -z "$text"]; then
   echo "The text parameter is required"
   exit
fi

ext=$2
if [ -z "$ext" ]; then
    grep -rnHI "$text" *
else
    grep --include "*.$ext" -rnHI "$text" *
fi

Usage

grepr TEXT EXT

TEXT
– required
– contains the text to search for

EXT
– optional
– the extension of files to search in

Example

grepr WEB_DIR

This will search for the string “WEB_DIR” in all files in the current folder and all the folders in the current folder.

Or to search in a specific type of files:

grepr WEB_DIR php

This will search for the string “WEB_DIR” in files with the “php” extension in the current folder and all the folders in the current folder.

Output

user@system:/etc/apache2$ grepr TraceEnable
conf.d/security:49:TraceEnable Off

Grep command

The grep command used is:

grep --include "*.$ext" -rnHI "$text" *

The information below is mostly from the manpage and explains the used options in the command above.

Searching in a specific type of files

–include=PATTERN
Recurse in directories only searching file matching PATTERN.

Using grep recursively

-R, -r, –recursive
Read all files under each directory, recursively; this is equivalent to the -d recurse option.

Dipslay the line numbers

-n, –line-number
Prefix each line of output with the line number within its input file.

Display the file name

-H, –with-filename
Print the filename for each match.

Skip binaries

-I
Process a binary file as if it did not contain matching data; this is equivalent to the –binary-files=without-match option.