Similar commands :

grep, egrep, fgrep - print lines matching a pattern

Description :

Grep searches the named input FILEs (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -EFgrep is the same as grep -F.

Examples : 

Search a word in all files of current directory.

grep "PATTERN"

Search a word in a single or multiple files

grep -ir "PATTERN" test.txt /path/

grep -ir "PATTERN" test.txt test2.txt /path/
grep -ir --include=PATTERN "PATTERN" /path/
grep -ir --include={*.txt,*.php,*.jsp} "PATTERN" /path/

Search a word excluding a specific or multiple files

grep -r --exclude=PATTERN "PATTERN" /path/

grep -r --exclude=PATTERN --exclude=PATTERN "PATTERN" /path/
grep -r --exclude={*.txt,*.asp,*.json} "PATTERN" /path/

Search a word recursively in sub directory excluding single or multiple directory

grep -R --exclude-dir=PATTERN "PATTERN" /path/

grep -R --exclude-dir={dir1,dir2,dir3} "PATTERN" /path/
grep -R --exclude-dir=PATTERN --exclude-dir=PATTERN "PATTERN" /path/

Print single file once when multiple occurance.

grep -rc --exclude="bak_*" "PATTERN" | grep -v :0

Print serveral surrounding lines.

#Before & After
grep -B3 -A2 foo README.txt

#Both before & after
grep -C3 foo README.txt


-i = ignore case sensitive
-c = count of words found
-v = print inverts the match
--color = force grep to display output in colors
-R = Recursively
-H = with filename
-h = without filename
-B2 = print before 2 lines
-A2 = print after 2 lines
-C2 = print before 2 lines & after 2 lines

"PATTERN" = any regex or any string
/path/ = path where to search


  • linux
  • grep