Linux grep and ripgrep Cheat Sheet

Search text with grep, egrep, fgrep, and ripgrep including regex, file globs, recursion, and context.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Basic grep
Search for a word
grep ERROR app.log

# Print lines containing a pattern.

Case-insensitive search
grep -i timeout app.log

# Match regardless of uppercase or lowercase.

Show line numbers
grep -n TODO src/app.js

# Display line numbers with matches.

Count matching lines
grep -c ERROR app.log

# Only show the number of matches.

Invert a match
grep -v '^#' .env

# Print lines that do not match.

Match whole words only
grep -w user auth.log

# Avoid partial substring matches.

## Regex with grep
Use extended regex
grep -E 'warn|error|fatal' app.log

# Enable `+`, `?`, and alternation without heavy escaping.

Match literal text only
grep -F 'a+b*c' notes.txt

# Disable regex interpretation.

Match line start and end
grep '^ERROR.*timeout$' app.log

# Search with anchors.

Find blank lines
grep -n '^$' file.txt

# Search for empty lines.

Find non-blank lines
grep -n '[^[:space:]]' file.txt

# Show lines containing at least one non-space character.

## Recursive Search
Search recursively
grep -R 'TODO' src/

# Search all files under a directory.

Recursive search with line numbers
grep -Rn 'TODO' src/

# Show file names and line numbers for matches.

Only search matching file names
grep -R --include='*.ts' 'useEffect' src/

# Restrict recursive search to certain extensions.

Exclude directories
grep -R --exclude-dir=node_modules 'axios' .

# Skip noisy folders like node_modules or dist.

List matching file names only
grep -Rl 'TODO' src/

# Show only files that contain a match.

## Context Around Matches
Show lines before a match
grep -B 3 ERROR app.log

# Print 3 lines before each match.

Show lines after a match
grep -A 5 ERROR app.log

# Print 5 lines after each match.

Show lines before and after
grep -C 2 ERROR app.log

# Print context on both sides of a match.

## ripgrep (rg)
Search recursively with ripgrep
rg TODO src/

# Fast codebase search.

Search with line numbers
rg -n 'useState' src/

# Show matches with file and line context.

Search only specific file types
rg -g '*.ts' 'useEffect' src/

# Restrict search by glob.

Include hidden files
rg --hidden 'apiKey' .

# Search dotfiles and hidden paths.

Literal string search in ripgrep
rg -F 'http://localhost:3000' .

# Disable regex parsing for a search term.

List files containing matches
rg -l 'TODO|FIXME' src/

# Return only matching file names.

Recommended next

No recommendations yet.