Grep

Essential grep commands for searching text patterns in files and streams.

cli
greplinuxsearchregexterminal

Basic Usage

# Search for pattern in file
grep "pattern" file.txt

# Search in multiple files
grep "pattern" file1.txt file2.txt
grep "pattern" *.txt

# Search recursively in directory
grep -r "pattern" /path/to/dir
grep -R "pattern" .  # Include symlinks

# Search from stdin (pipe)
cat file.txt | grep "pattern"
echo "hello world" | grep "world"

Common Options

# Case-insensitive search
grep -i "pattern" file.txt

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

# Count matching lines
grep -c "pattern" file.txt

# Show only matching part
grep -o "pattern" file.txt

# Invert match (non-matching lines)
grep -v "pattern" file.txt

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

# Show filenames only
grep -l "pattern" *.txt   # Files with matches
grep -L "pattern" *.txt   # Files without matches

Context Options

# Show lines before match
grep -B 3 "pattern" file.txt

# Show lines after match
grep -A 3 "pattern" file.txt

# Show lines before and after (context)
grep -C 3 "pattern" file.txt

# Separate matches with delimiter
grep --group-separator="---" -C 2 "pattern" file.txt

Regular Expressions

# Basic regex (BRE) - default
grep "^start" file.txt      # Line starts with
grep "end$" file.txt        # Line ends with
grep "a.b" file.txt         # Any single character
grep "a*" file.txt          # Zero or more
grep "a\+" file.txt         # One or more (escaped in BRE)
grep "a\?" file.txt         # Zero or one (escaped in BRE)
grep "[abc]" file.txt       # Character class
grep "[^abc]" file.txt      # Negated character class
grep "[a-z]" file.txt       # Character range

# Extended regex (ERE)
grep -E "a+" file.txt       # One or more
grep -E "a?" file.txt       # Zero or one
grep -E "a{2,4}" file.txt   # 2 to 4 occurrences
grep -E "a|b" file.txt      # Alternation (OR)
grep -E "(abc)+" file.txt   # Grouping

# Perl-compatible regex (PCRE)
grep -P "\d+" file.txt      # Digits
grep -P "\w+" file.txt      # Word characters
grep -P "\s+" file.txt      # Whitespace
grep -P "(?<=@)\w+" file.txt  # Lookbehind

Multiple Patterns

# Match any of multiple patterns
grep -e "pattern1" -e "pattern2" file.txt

# Patterns from file
grep -f patterns.txt file.txt

# Using extended regex OR
grep -E "pattern1|pattern2" file.txt

# Match all patterns (AND logic)
grep "pattern1" file.txt | grep "pattern2"

Output Control

# Suppress error messages
grep -s "pattern" file.txt

# Quiet mode (exit status only)
grep -q "pattern" file.txt && echo "Found"

# Print filename with matches
grep -H "pattern" file.txt

# Suppress filename (multiple files)
grep -h "pattern" *.txt

# Add color highlighting
grep --color=auto "pattern" file.txt
grep --color=always "pattern" file.txt

# Null-separated output (for xargs)
grep -Z -l "pattern" *.txt | xargs -0 rm
# Recursive search
grep -r "pattern" /path

# Include specific files
grep -r --include="*.js" "pattern" .

# Exclude specific files
grep -r --exclude="*.log" "pattern" .

# Exclude directories
grep -r --exclude-dir=node_modules "pattern" .
grep -r --exclude-dir={node_modules,dist} "pattern" .

# Follow symlinks
grep -R "pattern" .

Binary Files

# Treat binary as text
grep -a "pattern" binary_file

# Skip binary files
grep -I "pattern" *

# Show binary file matches
grep --binary-files=text "pattern" file

Performance Tips

# Fixed string (faster, no regex)
grep -F "literal string" file.txt
fgrep "literal string" file.txt  # Equivalent

# Limit to first N matches
grep -m 5 "pattern" file.txt

# Use parallel processing (with xargs)
find . -name "*.txt" | xargs -P 4 grep "pattern"

Practical Examples

# Find TODO comments in code
grep -rn "TODO" --include="*.js" .

# Find IP addresses
grep -E "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" file.txt

# Find email addresses
grep -E "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}" file.txt

# Find empty lines
grep "^$" file.txt

# Find non-empty lines
grep -v "^$" file.txt

# Find lines with only whitespace
grep "^[[:space:]]*$" file.txt

# Find function definitions (JavaScript)
grep -E "function\s+\w+\s*\(" *.js

# Find imports/requires
grep -E "^(import|const.*require)" *.js

# Count occurrences per file
grep -c "pattern" *.txt | grep -v ":0$"

# Find files not containing pattern
grep -rL "pattern" --include="*.txt" .

# Extract URLs from file
grep -oE "https?://[^\"' >]+" file.html

Exit Codes

# Exit codes
# 0 - Match found
# 1 - No match found
# 2 - Error occurred

# Use in scripts
if grep -q "pattern" file.txt; then
  echo "Pattern found"
else
  echo "Pattern not found"
fi

Alternatives

# ack - Better for code searching
ack "pattern"

# ag (The Silver Searcher) - Faster
ag "pattern"

# ripgrep (rg) - Fastest
rg "pattern"