Skip to main content

grep Cheatsheet

By Dejan Panovski Updated on Download PDF

Quick reference for the grep text search command

Grep searches text for patterns and prints matching lines. This cheatsheet covers common grep options for file searches, recursion, context output, and regex patterns.

Find matching lines in a file.

CommandDescription
grep "pattern" file.txtSearch a single file
grep -i "pattern" file.txtCase-insensitive search
grep -n "pattern" file.txtShow line numbers
grep -v "pattern" file.txtInvert match
grep -w "word" file.txtMatch whole words

Multiple Files

Search across multiple files.

CommandDescription
grep "pattern" file1 file2Search specific files
grep "pattern" *.logSearch by glob
grep -l "pattern" *.logShow matching filenames
grep -L "pattern" *.logShow non-matching filenames

Search directories recursively.

CommandDescription
grep -r "pattern" dir/Recursive search
grep -R "pattern" dir/Follow symlinks
grep -r --include="*.conf" "pattern" dir/Include file types
grep -r --exclude="*.log" "pattern" dir/Exclude file types

Context Output

Show lines around matches.

CommandDescription
grep -C 3 "pattern" file.txt3 lines before and after
grep -A 2 "pattern" file.txt2 lines after
grep -B 2 "pattern" file.txt2 lines before

Count and Only Matches

Summarize or extract matches.

CommandDescription
grep -c "pattern" file.txtCount matching lines
grep -o "pattern" file.txtOnly the matching part
grep -m 1 "pattern" file.txtStop after 1 match

Extended Regex

Use more powerful patterns.

CommandDescription
grep -E "foo|bar" file.txtAlternation
grep -E "colou?r" file.txtOptional character
grep -E "[0-9]{3}" file.txtRepetition
grep -E "^start" file.txtLine starts with
grep -E "end$" file.txtLine ends with

Common Options

Useful flags to remember.

OptionDescription
-iIgnore case
-nShow line numbers
-vInvert match
-wMatch whole words
-rRecursive search
-EExtended regex
-FFixed strings (no regex)
-HAlways show filename
-qQuiet mode (exit status only)