Grep Cheatsheet

Pattern matching, regex, recursive search & common options

Linux / Command
Contents
🔍

Basics

# Search in file
grep "pattern" file.txt
grep "error" /var/log/syslog

# Case insensitive
grep -i "error" file.txt

# Invert match (lines NOT matching)
grep -v "debug" file.txt

# Count matches
grep -c "error" file.txt

# Show line numbers
grep -n "error" file.txt

# Show only matching part
grep -o "[0-9]\+" file.txt

# Whole word match
grep -w "error" file.txt

# Multiple patterns
grep -e "error" -e "warn" file.txt
grep "error\|warn" file.txt
📐

Regex Patterns

# Basic regex (default)
.          # any character
*          # zero or more of previous
^          # start of line
$          # end of line
[abc]      # character class
[^abc]     # negated class
[a-z]      # range

# Extended regex (-E or egrep)
grep -E "pattern" file.txt

+          # one or more
?          # zero or one
{n}        # exactly n
{n,m}      # n to m times
(a|b)      # alternation
()         # grouping

# Character classes
\d  or [0-9]       # digit
\w  or [a-zA-Z_]   # word char
\s  or [ \t]       # whitespace
\b                  # word boundary
⚙️

Options

-i    # case insensitive
-v    # invert match
-c    # count
-n    # line numbers
-l    # files with matches only
-L    # files without matches
-o    # only matching part
-w    # whole word
-x    # whole line
-m N  # stop after N matches
-q    # quiet (exit status only)
-E    # extended regex
-P    # Perl regex (PCRE)
-F    # fixed string (no regex)
-r    # recursive
-R    # recursive + follow symlinks
-h    # suppress filename
-H    # always show filename
📂

Recursive Search

# Search all files recursively
grep -r "TODO" .
grep -rn "TODO" src/

# Include/exclude files
grep -r --include="*.py" "import" .
grep -r --exclude="*.log" "error" .
grep -r --exclude-dir=node_modules "TODO" .
grep -r --exclude-dir={node_modules,.git} "TODO" .

# List matching files only
grep -rl "TODO" src/
📄

Context Lines

# Lines after match
grep -A 3 "error" file.txt

# Lines before match
grep -B 3 "error" file.txt

# Lines before & after
grep -C 3 "error" file.txt
🚀

Advanced

# Perl regex (advanced patterns)
grep -P "\d{3}-\d{4}" file.txt    # phone numbers
grep -P "(?<=@)\w+" file.txt      # domain after @

# Binary files
grep -a "pattern" binary_file     # treat as text
grep -I "pattern" *               # skip binaries

# With find
find . -name "*.py" -exec grep -l "TODO" {} +

# Colorize output
grep --color=always "pattern" file.txt
💡

Common Examples

# IP addresses
grep -oE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" log.txt

# Email addresses
grep -oE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+" file.txt

# Empty lines
grep -c "^$" file.txt

# Lines starting with #
grep "^#" config.txt

# Log errors in last 100 lines
tail -100 app.log | grep -i "error\|fail\|critical"

# Count unique IPs
grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log | sort -u | wc -l