VOOZH about

URL: https://dev.to/cameroonreevesdev/grep-command-cheat-sheet-all-flags-usage-examples-3h1e

⇱ grep Command Cheat Sheet — All Flags & Usage Examples - DEV Community


Originally published at commandinline.com.

The grep command searches files for lines matching a pattern and is the single most-used text tool in any Unix admin's daily workflow. This cheat sheet covers basic and extended regex, recursion, context lines, file-type filtering, and the speed tricks that make multi-gigabyte log spelunking practical. Pair it with awk for column extraction or sed when you need to transform matches in place.

Quick Reference

grep PATTERN FILE finds matching lines. Add -i for case-insensitive, -v to invert, -r to recurse, -n for line numbers, -l for filenames only, -c for counts, -A/-B/-C N for context lines, -E for extended regex, and -F for fixed strings. --include='*.py' filters file types during recursion.

Syntax & Common Options

The general form is grep [OPTIONS] PATTERN [FILE...]. When no file is given, grep reads stdin.

grep [OPTIONS] PATTERN [FILE...]
 -i # case-insensitive
 -v # invert match (lines NOT matching)
 -r / -R # recursive (R follows symlinks)
 -n # show line numbers
 -l # only print filenames with matches
 -L # only print filenames WITHOUT matches
 -c # count of matching lines per file
 -o # print only the matching part
 -w # match whole words
 -x # match whole lines
 -E # extended regex (egrep)
 -F # fixed string, no regex (fgrep)
 -P # Perl-compatible regex (PCRE)
 -A N # N lines after match
 -B N # N lines before match
 -C N # N lines of context (before AND after)
 --include='GLOB' # only search matching files
 --exclude-dir=DIR # skip directories

Syntax

Quote your pattern to keep the shell from expanding it. Single quotes are safest for regex characters like $, *, and parentheses.

# Basic search
grep 'ERROR' /var/log/syslog

# Multiple files
grep 'timeout' /var/log/nginx/*.log

# Read from stdin
journalctl -u sshd | grep 'Failed password'

# Search recursively under a directory
grep -r 'TODO' src/

# Use -e to combine multiple patterns
grep -e 'ERROR' -e 'WARN' -e 'CRITICAL' app.log

Quick Reference Table

The patterns and flags that solve 90% of real searches.

# Find IP addresses (basic POSIX regex with -E)
grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}' access.log

# Lines starting with ERROR
grep '^ERROR' app.log

# Lines ending in a digit
grep '[0-9]$' data.txt

# Empty lines
grep '^$' file.txt

# Non-empty lines (invert empty)
grep -v '^$' file.txt

# Comments and blanks (typical for cleaning configs)
grep -Ev '^(#|$)' /etc/ssh/sshd_config

Common Flags

Day-to-day combinations that show up in incident response and code search.

# Case-insensitive recursive search with line numbers
grep -rin 'connection refused' /var/log/

# Count occurrences per file
grep -c 'ERROR' /var/log/*.log

# Only print filenames that contain a match
grep -rl 'API_KEY' .

# Exclude vendor and node_modules from a code search
grep -r 'TODO' . --exclude-dir={node_modules,vendor,.git}

# Search only Python files
grep -rn --include='*.py' 'import requests' .

# Show 3 lines of context around each match
grep -C 3 'segfault' /var/log/kern.log

Practical Examples

Real diagnostic and admin patterns.

# Find failed SSH logins with usernames
grep 'Failed password' /var/log/auth.log | awk '{print $9, $11}'

# Pull all 5xx responses from an Nginx access log
grep -E ' 5[0-9]{2} ' /var/log/nginx/access.log

# Locate a process listening on a specific port
ss -tnlp | grep ':443'

# Find all files containing a deprecated API call
grep -rln --include='*.go' 'ioutil.ReadAll' .

# Extract just the matching email addresses
grep -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+' contacts.txt

# Show 10 lines after every "panic" entry
grep -A 10 'panic:' /var/log/syslog

Tips and Tricks

Performance and ergonomics tricks that pay off on big trees.

# Combine -F with a file of fixed strings (huge speedup)
grep -Ff blocked_ips.txt access.log

# Set GREP_COLORS for custom highlight (or use --color=always)
export GREP_COLOR='1;31' # bright red matches
export GREP_OPTIONS='' # avoid (deprecated, breaks scripts)

# Use --color=auto in interactive shells, never in scripts
alias grep='grep --color=auto'

# When grep is too slow, switch to ripgrep (rg) — same flags
rg -i 'pattern' .

# Use -P for lookarounds and \d shortcuts (PCRE)
grep -P '(?<=user=)\w+' /var/log/auth.log

Common Pitfalls

  • "grep: invalid option" — your pattern starts with -. Use -- or -e: grep -e '-foo' file.
  • "Binary file matches" — pass -a to treat as text, or -I to skip binaries entirely.
  • No matches when you expect them — check case (-i), check whether you need -E for +/?, and confirm the file actually contains the pattern with cat -A.
  • Recursive search hangs — you crossed into /proc or a network mount. Add --exclude-dir or use -r instead of -R.

Pro Tips

  • Pipe through grep --color=always | less -R to keep highlights when paging.
  • Use grep -B 1 -A 1 'KEY:' to show YAML/INI keys with surrounding context.
  • zgrep, bzgrep, and xzgrep search compressed logs without decompressing first.
  • Replace grep | wc -l with grep -c — saves a process and works on big files.

Related Commands

Master a dozen of these patterns and you will replace half your "open the file in an editor" reflex with a one-line grep.