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

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

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

Search a word excluding a specific or multiple files

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

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

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

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

#multiple
grep -R --exclude-dir={dir1,dir2,dir3} "PATTERN" /path/
or
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

OPTIONS

-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