grep cheat sheet

Basics
grep [pattern] FILE
grep ‘^[A,E].*o’ f.txtFind a string starting with A or E and ending in o
grep -f pat.txt f.txtScan f.txt, using contents of pat.txt as regex
grep -i Gnu f.txtFind “gnu” in f.txt, ignoring capitalization
grep -v gnu f.txtFind all lines not containing “gnu” (invert match)
grep -w ‘a.*o’ f.txtFind whole word matches only, ignoring substrings
grep -x ‘a.*o’ f.txtFind whole line matches only, as in ^(a.*o)$

Output
-cPrint only the number of lines containing a match
–colo[u]rDisplay matches in color
-lPrint the names of files with matches
-LPrint the names of files searched that contained no matches
-oPrint only the matched part of a line
-sSuppress errors (such as non-existent or unreadable files)
-A nPrint n number of lines after a matching line
-B nPrint n number of lines before a matching line
-C nPrint n number of lines before and after a matching line

Output prefixes
-bPrint the byte offset of the match within the input file
-HPrint the filename containing a match
-hDo not print the filename containing a match
-nPrint the line number of each match
-TPrint an initial Tab before matches so that output is neatly aligned

File and directory selection
-aProcess a binary file as if it were text
-D <skip|read>Skip or read a FIFO, device, or socket
-d <skip|read|recurse>Skip, read, or recurse through a directory
–exclude ‘*.sh’Do not search any file with the .sh suffix
–exclude-from FILESkip any file listed in FILE
–exclude-dir *fooSkip any directory ending in foo
-rWhen a directory is encountered, search files in it
-RSearch directories and follow symlinks

Variants
-GUse basic regex (this is the default)
-EExtended regex
-FInterpret the search pattern as a fixed string, not regex
-PUse Perl regex (PCRE)

Regular expression
.Any single character
?Match preceding item zero or one time
*Match preceding item zero or more times
+Match preceding item one or more times
{2}Match preceding item two times
{3,}Match preceding item three or more times
{,4}Match preceding item at most four times
{1,5}Match preceding item at least once, but no more than five times
[A,B]Match A or B
[3-9]Match all digits 3 to 9
^Start of a line
$End of a line
\sSpace
[:alnum:]Alphanumeric character
[:alpha:]Alphabetic character
[:digit:]Digits 0 through 9
[:punct:]Punctuation
[:space:]Space