##grep
ref: www.hackingnote.com
##Count Occurrence: -c
TEXT
$ cat example.txt | grep -c good
2
##Get Context: -C
Set --context=0 to print that line alone
TEXT
$ cat example.txt | grep --context=0 "good luck"
good luckSet --context=1 to print 1 line below and 1 line above
TEXT
$ cat example.txt | grep --context=1 "good luck"
hello world
good luck
good dayor use -C 1
TEXT
$ cat example.txt | grep -C 1 "good luck"
hello world
good luck
good day
##Ignore: -v
Use -v to exclude some lines(i.e. NOT)
TEXT
$ cat example.txt | grep good | grep -v day
good luck
##Case Insensitive: -i
TEXT
$ cat example.txt | grep GOOD
$ cat example.txt | grep -i GOOD
good luck
good day
##Show Match in Color: --color
TEXT
$ cat example.txt | grep good --color
##Show Matched Line Number: -n
TEXT
$ cat example.txt | grep good -n
2:good luck
3:good day
##Show Matched File Name: -l
grep is not limited to searching a single file, compare the results below
TEXT
$ grep good example.txt
good luck
good dayto search from multiple files:
TEXT
$ grep good *
example.txt:good luck
example.txt:good dayfilename will be shown along with the matched lines; to show the filename only:
TEXT
$ grep -l good *
example.txtwhat happens to the “pipe” version?
TEXT
$ cat example.txt | grep good -l
(standard input)
##Search for Whole Words Only: -w
TEXT
$ grep -w goo example.txtthis returns nothing since goo is a pattern though not a whole word
TEXT
$ grep goo example.txt
good luck
good day
##Recursive grep: -R
This will search all the directory and sub-directories recursively
TEXT
$ grep -R pattern *
##Set Maximum Matches: -m
TEXT
$ cat example.txt | grep -m 1 good
good luck##Match
Show ssh processes
TEXT
$ ps | grep sshSpecify max count by -m:
TEXT
$ cat foo.log | grep -m 10 ERROR##Show file name
TEXT
grep -H##grep vs egrap vs fgrep
grep, egrep and fgrep are used to match patterns in files, here are the differences:
grep: basic regular expressionsegrep: extended regular expressions(?,+,|), equivalent togrep -Efgrep: fixed patterns, no regular expression; faster than grep and egrep; equivalent togrep -FCheckout the Regular_expression wikipedia page for the definitions of POSIX basic and extended regular expressions Assume there’s aexamle.txtfile containing 4 lines:
TEXT
$ cat example.txt
hello world
good luck
good day
linux
###grep vs fgrep
fgrep does not support regular expression at all, this will return nothing
TEXT
$ cat example.txt | fgrep g..duse grep instead
TEXT
$ cat example.txt | grep g..d
good luck
good day
###grep vs egrep
grep does not support |, so this will return nothing
TEXT
$ cat example.txt | grep "good|linux"however egrep can recognize | as OR
TEXT
$ cat example.txt | egrep "good|linux"
good luck
good day
linux