This cheat sheet is intended to be a quick reminder for the main concepts involved in using the command line p.
Search standard output (i.e. a stream of text)
$ grep [options] search_string
Search for an exact string in file:
$ grep [options] search_string path/to/file
Print lines in myfile.txt containing the string "mellon"
$ grep 'mellon' myfile.txt
Wildcards are accepted in filename.
-i β grep -i ^DA demo.txt β Forgets about case sensitivity
-w β grep -w "of" demo.txt β Search only for the full word
-A β grep -A 3 'Exception' error.log β Display 3 lines after matching string
-B β grep -B 4 'Exception' error.log β Display 4 lines before matching string
-C β grep -C 5 'Exception' error.log β Display 5 lines around matching string
-r β grep -r 'quickref.me' /var/log/nginx/ β Recursive search (within subdirs)
-v β grep -v 'warning' /var/log/syslog β Return all lines which don't match the pattern
-e β grep -e '^al' filename β Use regex (lines starting with 'al')
-E β grep -E 'ja(s|cks)on' filename β Extended regex (lines containing jason or jackson)
-c β grep -c 'error' /var/log/syslog β Count the number of matches
-l β grep -l 'robot' /var/log/* β Print the name of the file(s) of matches
-o β grep -o search_string filename β Only show the matching part of the string
-n β grep -n "go" demo.txt β Show the line numbers of the matches
Regex syntax (quickref.me) Regex examples (quickref.me)
Please refer to the full version of the regex cheat sheet for more complex requirements.
. β Any character.
? β Optional and can only occur once.
* β Optional and can occur more than once.
+ β Required and can occur more than once.
{n} β Previous item appears exactly n times.
{n,} β Previous item appears n times or more.
{,m} β Previous item appears n times maximum.
{n,m} β Previous item appears between n and m times.
[:alpha:] β Any lower and upper case letter.
[:digit:] β Any number.
[:alnum:] β Any lower and upper case letter or digit.
[:space:] β Any whitesΒpace.
[A-ZΒa-z] β Any lower and upper case letter.
[0-9] β Any number.
[0-9ΒA-ZΒa-z] β Any lower and upper case letter or digit.
^ β Beginning of line.
$ β End of line.
^$ β Empty line.
\< β Start of word.
\> β End of word.