| Basics | |
| grep [pattern] FILE | |
| grep ‘^[A,E].*o’ f.txt | Find a string starting with A or E and ending in o |
| grep -f pat.txt f.txt | Scan f.txt, using contents of pat.txt as regex |
| grep -i Gnu f.txt | Find “gnu” in f.txt, ignoring capitalization |
| grep -v gnu f.txt | Find all lines not containing “gnu” (invert match) |
| grep -w ‘a.*o’ f.txt | Find whole word matches only, ignoring substrings |
| grep -x ‘a.*o’ f.txt | Find whole line matches only, as in ^(a.*o)$ |
Output | |
| -c | Print only the number of lines containing a match |
| –colo[u]r | Display matches in color |
| -l | Print the names of files with matches |
| -L | Print the names of files searched that contained no matches |
| -o | Print only the matched part of a line |
| -s | Suppress errors (such as non-existent or unreadable files) |
| -A n | Print n number of lines after a matching line |
| -B n | Print n number of lines before a matching line |
| -C n | Print n number of lines before and after a matching line |
Output prefixes | |
| -b | Print the byte offset of the match within the input file |
| -H | Print the filename containing a match |
| -h | Do not print the filename containing a match |
| -n | Print the line number of each match |
| -T | Print an initial Tab before matches so that output is neatly aligned |
File and directory selection | |
| -a | Process 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 FILE | Skip any file listed in FILE |
| –exclude-dir *foo | Skip any directory ending in foo |
| -r | When a directory is encountered, search files in it |
| -R | Search directories and follow symlinks |
Variants | |
| -G | Use basic regex (this is the default) |
| -E | Extended regex |
| -F | Interpret the search pattern as a fixed string, not regex |
| -P | Use 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 |
| \s | Space |
| [:alnum:] | Alphanumeric character |
| [:alpha:] | Alphabetic character |
| [:digit:] | Digits 0 through 9 |
| [:punct:] | Punctuation |
| [:space:] | Space |