Skip to content

Grep Cheat Sheet

Search for patterns in files and streams.

Basic Syntax

grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] -e PATTERN -e PATTERN [FILE...]

Most-Used Flags

Flag What it does Example
-i Case-insensitive grep -i "error" log.txt
-n Show line numbers grep -n "error" log.txt
-c Count matching lines grep -c "error" log.txt
-v Invert — lines that do NOT match grep -v "debug" log.txt
-l Only print filenames grep -l "TODO" *.sh
-r Recursive through directories grep -r "TODO" ~/scripts/
-w Whole word match grep -w "err" log.txt
-x Whole line match grep -x "done" status.txt
-o Print only matched portion grep -o "[0-9]\+" data.txt
-A N N lines after match grep -A 3 "ERROR" log.txt
-B N N lines before match grep -B 2 "ERROR" log.txt
-C N N lines before and after grep -C 2 "ERROR" log.txt
-E Extended regex (ERE) grep -E "(error\|warn)" log.txt
-P Perl-compatible regex grep -P "\d{4}-\d{2}-\d{2}" log.txt
-F Fixed string (no regex) grep -F "error.c" log.txt
-q Quiet — exit code only grep -q "error" log.txt && echo "found"
--color Highlight matches grep --color "error" log.txt

Patterns

grep "^#" file.txt           # lines starting with #
grep "\.sh$" file.txt        # lines ending with .sh
grep "^$" file.txt           # blank lines
grep "." file.txt            # any non-empty line
grep -E "[0-9]{4}" file.txt  # 4-digit number
grep -w "root" /etc/passwd   # whole word "root"

Common Recipes

# Find files containing a pattern
grep -rl "pattern" /path/to/search/

# Count occurrences (not lines) with grep + wc
grep -o "pattern" file.txt | wc -l

# Find lines matching A AND B (both)
grep "A" file.txt | grep "B"

# Find lines matching A OR B
grep -E "A|B" file.txt

# Exclude multiple patterns
grep -v "debug\|info\|verbose" log.txt

# Case-insensitive recursive search, show filename and line
grep -rni "todo" ~/projects/

# Search only files of a type
grep -r --include="*.sh" "set -e" ~/scripts/

# Search compressed logs
zgrep "error" /var/log/syslog.gz

Exit Codes

Code Meaning
0 Match found
1 No match
2 Error (bad file, bad option)

Use this in scripts:

if grep -q "error" "$LOGFILE"; then
    echo "Errors found"
fi

Related: awk, sed, pipes-redirection