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.

SysOps·38 commands·Last updated 2026-07-21
grepText Searchlinux

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" file
Extended regex (equivalent to egrep)
grep "^start" file
Match line start
grep "end$" file
Match line end
grep "\<word\>" file
Match word boundary
grep -w "word" file
Match whole word
grep "[0-9]" file
Match digits
grep "[^0-9]" file
Match non-digits
grep "a\|b" file
Match a or b (BRE)
grep -E "a|b" file
Match a or b (ERE)

Context 4

grep -A 3 "pattern" file
Show 3 lines after each match
grep -B 2 "pattern" file
Show 2 lines before each match
grep -C 3 "pattern" file
Show 3 lines before and after each match
grep -A 3 -B 2 "pattern" file
2 lines before and 3 after

Multiple Patterns & Files 6

grep -e "pattern1" -e "pattern2" file
Match multiple patterns
grep -f patterns.txt file
Read patterns from a file
grep "pattern" file1 file2
Search multiple files
grep "pattern" *.log
Search files matched by a wildcard
grep -H "pattern" file
Show file name
grep -h "pattern" file1 file2
Suppress file name

Common Patterns 5

grep "error\|warning" app.log
Search 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.log
Extract IP addresses
grep -c "^$" file
Count 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