grep Cheatsheet - Linux Text Search Reference
For pulling errors out of logs or finding every reference to an identifier in a repo, grep is the fastest entry point. Remember -r for recursive, -i for ignore case, -C for context, and -E for extended regex and you cover most searches — and avoid finding a match without any context.
Basic Search 7
grep "pattern" fileSearch for matches in a file
grep -i "pattern" fileCase-insensitive search
grep -v "pattern" fileInvert match (exclude)
grep -c "pattern" fileCount matching lines
grep -n "pattern" fileShow line numbers
grep -o "pattern" fileOutput only the matched part
grep -q "pattern" fileQuiet mode (returns only exit code)
Recursive 7
grep -r "pattern" dir/Recursively search a directory
grep -R "pattern" dir/Recursive search (follow symlinks)
grep -rn "pattern" dir/Recursive with line numbers
grep -rl "pattern" dir/Output only matching file names
grep -r --include="*.log" "pattern" dir/Search only a given file type
grep -r --exclude="*.tmp" "pattern" dir/Exclude a given file type
grep -r --exclude-dir="node_modules" "pattern" dir/Exclude a directory
Regular Expression 9
grep -E "pattern" fileExtended regex (equivalent to egrep)
grep "^start" fileMatch line start
grep "end$" fileMatch line end
grep "\<word\>" fileMatch word boundary
grep -w "word" fileMatch whole word
grep "[0-9]" fileMatch digits
grep "[^0-9]" fileMatch non-digits
grep "a\|b" fileMatch a or b (BRE)
grep -E "a|b" fileMatch a or b (ERE)
Context 4
grep -A 3 "pattern" fileShow 3 lines after each match
grep -B 2 "pattern" fileShow 2 lines before each match
grep -C 3 "pattern" fileShow 3 lines before and after each match
grep -A 3 -B 2 "pattern" file2 lines before and 3 after
Multiple Patterns & Files 6
grep -e "pattern1" -e "pattern2" fileMatch multiple patterns
grep -f patterns.txt fileRead patterns from a file
grep "pattern" file1 file2Search multiple files
grep "pattern" *.logSearch files matched by a wildcard
grep -H "pattern" fileShow file name
grep -h "pattern" file1 file2Suppress file name
Common Patterns 5
grep "error\|warning" app.logSearch for error or warning
grep -rn "TODO\|FIXME" src/Find TODO/FIXME in code
grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.logExtract IP addresses
grep -c "^$" fileCount empty lines
grep -v "^#" file | grep -v "^$"Exclude comments and blank lines
Tips
- grep uses BRE (basic regex) by default; +, ?, | must be escaped or enable ERE with -E.
- When searching large directories recursively, exclude node_modules, .git, etc. with --exclude-dir.
- grep -q is useful in scripts to test for a match — it outputs nothing and returns only an exit code.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us