grep
Website: https://www.gnu.org/software/grep/ CLI Tool: grep Authentication: N/A
Description
grep (Global Regular Expression Print) searches text using patterns. It's one of the most essential Unix tools for finding text in files, filtering command output, and processing log files. Supports regular expressions for powerful pattern matching.
Commands
Basic Search
Search in File
grep "pattern" file.txt
grep "error" log.txt
grep 'keyword' file.txt
Search for pattern in file.
Search Multiple Files
grep "pattern" file1.txt file2.txt
grep "error" *.log
grep "pattern" dir/*
Search in multiple files.
Recursive Search
grep -r "pattern" directory/
grep -R "pattern" .
grep -r "TODO" src/
Search recursively in directories.
Case Insensitive
grep -i "pattern" file.txt
grep -i "error" log.txt
Ignore case when searching.
Whole Word
grep -w "word" file.txt
grep -w "error" log.txt
Match whole words only.
Line Numbers
grep -n "pattern" file.txt
grep -n "error" log.txt
Show line numbers.
Pattern Matching
Exact Match
grep "exact string" file.txt
grep 'hello world' file.txt
Search for exact string.
Regular Expression
grep "^pattern" file.txt
grep "pattern$" file.txt
grep "[0-9]+" file.txt
grep "user[0-9]" file.txt
Use regex patterns (^=start, $=end).
Extended Regex
grep -E "pattern1|pattern2" file.txt
grep -E "[0-9]{3}-[0-9]{4}" file.txt
egrep "pattern1|pattern2" file.txt
Use extended regex (ERE).
Perl Regex
grep -P "\d{3}-\d{4}" file.txt
grep -P "(?<=user:)\w+" file.txt
Use Perl-compatible regex (PCRE).
Fixed String
grep -F "literal.string" file.txt
fgrep "literal.string" file.txt
Treat pattern as fixed string (no regex).
Filtering Results
Invert Match
grep -v "pattern" file.txt
grep -v "comment" code.py
grep -v "^#" config.txt
Show lines that don't match.
Count Matches
grep -c "pattern" file.txt
grep -c "error" log.txt
Count matching lines.
Only Matching Part
grep -o "pattern" file.txt
grep -o "[0-9]+" file.txt
grep -o "http://[^[:space:]]+" file.txt
Print only matched parts.
Files with Matches
grep -l "pattern" *.txt
grep -l "TODO" src/*.js
List files with matches.
Files without Matches
grep -L "pattern" *.txt
List files without matches.
Quiet Mode
grep -q "pattern" file.txt
echo $? # 0 if found, 1 if not found
Silent mode (exit status only).
Context Display
Context Lines
grep -C 2 "pattern" file.txt
grep -C 3 "error" log.txt
Show N lines before and after match.
Before Context
grep -B 2 "pattern" file.txt
grep -B 5 "exception" log.txt
Show N lines before match.
After Context
grep -A 2 "pattern" file.txt
grep -A 5 "ERROR" log.txt
Show N lines after match.
File Selection
Include Files
grep --include="*.txt" -r "pattern" .
grep --include="*.log" -r "error" /var/log/
grep --include="*.{js,ts}" -r "function" src/
Search only matching files.
Exclude Files
grep --exclude="*.min.js" -r "pattern" .
grep --exclude="*.log" -r "pattern" .
Exclude matching files.
Exclude Directories
grep --exclude-dir="node_modules" -r "pattern" .
grep --exclude-dir={.git,dist,build} -r "pattern" .
Exclude directories from search.
Output Control
Colorize Output
grep --color=auto "pattern" file.txt
grep --color=always "error" log.txt | less -R
Highlight matches in color.
With Filename
grep -H "pattern" *.txt
Always print filename (default for multiple files).
Without Filename
grep -h "pattern" *.txt
Never print filename.
Byte Offset
grep -b "pattern" file.txt
Print byte offset of matches.
Max Count
grep -m 5 "pattern" file.txt
grep --max-count=10 "error" log.txt
Stop after N matches.
Binary Files
Binary File Handling
grep -a "pattern" binary.dat
grep --text "pattern" binary.dat
Treat binary files as text.
Skip Binary Files
grep -I "pattern" *
Skip binary files.
Multiple Patterns
OR Patterns
grep -e "pattern1" -e "pattern2" file.txt
grep "pattern1\|pattern2" file.txt
grep -E "pattern1|pattern2" file.txt
Match any of multiple patterns.
AND Patterns
grep "pattern1" file.txt | grep "pattern2"
Match all patterns (chain greps).
Pattern File
grep -f patterns.txt file.txt
grep --file=patterns.txt data.txt
Read patterns from file (one per line).
Special Patterns
Empty Lines
grep -E "^$" file.txt
grep -x "" file.txt
Match empty lines.
Non-Empty Lines
grep -v "^$" file.txt
Match non-empty lines.
Lines Starting With
grep "^word" file.txt
grep "^#" script.sh
Match lines starting with pattern.
Lines Ending With
grep "word$" file.txt
grep ";$" code.js
Match lines ending with pattern.
Performance
Line Buffered
grep --line-buffered "pattern" | other-command
Flush output on every line.
Max Files
grep -r --max-count=1 "pattern" .
Stop after first match per file.
Examples
Log File Analysis
# Find errors in logs
grep "ERROR" /var/log/app.log
# Find errors with context
grep -C 3 "ERROR" /var/log/app.log
# Count error types
grep -o "ERROR: [^:]*" app.log | sort | uniq -c
# Find recent errors
grep "ERROR" app.log | tail -20
# Find errors in compressed logs
zgrep "ERROR" app.log.gz
# Find errors excluding INFO
grep "ERROR" app.log | grep -v "INFO"
Code Search
# Find TODO comments
grep -r "TODO" src/
# Find function definitions
grep -n "function \w\+(" *.js
# Find import statements
grep -r "^import" src/
# Find specific function usage
grep -rw "myFunction" src/
# Find in specific file types
grep --include="*.py" -r "class " .
# Exclude directories
grep --exclude-dir={node_modules,.git} -r "pattern" .
Configuration Files
# Non-comment lines
grep -v "^#" config.txt | grep -v "^$"
# Find specific setting
grep "^server" nginx.conf
# Show setting with context
grep -A 5 "database" config.yml
# Compare configs
diff <(grep -v "^#" config1.txt) <(grep -v "^#" config2.txt)
Text Processing
# Extract emails
grep -oE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" file.txt
# Extract URLs
grep -oP "https?://[^\s]+" file.txt
# Extract IP addresses
grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" file.txt
# Extract phone numbers
grep -oE "\b[0-9]{3}-[0-9]{3}-[0-9]{4}\b" file.txt
# Count occurrences
grep -c "pattern" file.txt
Combining with Other Commands
# Filter process list
ps aux | grep "node"
# Find large files
ls -lh | grep "^-" | grep "G"
# Filter network connections
netstat -an | grep "ESTABLISHED"
# Search command history
history | grep "git"
# Filter environment variables
env | grep "PATH"
# Search in command output
find . -name "*.txt" | grep "test"
Multiple Pattern Matching
# Match multiple patterns (OR)
grep -E "error|warning|critical" log.txt
# Match multiple patterns from file
echo "error" > patterns.txt
echo "warning" >> patterns.txt
grep -f patterns.txt log.txt
# Match all patterns (AND)
grep "error" log.txt | grep "database" | grep "connection"
# Complex regex
grep -E "user[0-9]+@(gmail|yahoo)\.com" emails.txt
File Comparison
# Files containing pattern
grep -l "pattern" *.txt
# Files not containing pattern
grep -L "pattern" *.txt
# Count matches per file
grep -c "pattern" *.txt
# Show filenames with matches
grep -r -l "function" src/
# Recursive with file count
grep -r -c "TODO" src/ | grep -v ":0$"
Advanced Patterns
# Word boundaries
grep -w "var" code.js
# Case insensitive whole word
grep -iw "error" log.txt
# Multiple conditions
grep -E "^(error|warning):" log.txt
# Lookahead/lookbehind (with -P)
grep -P "(?<=user:)\w+" file.txt
# Character classes
grep "[[:digit:]]" file.txt
grep "[[:alpha:]]" file.txt
# Negated character class
grep "[^a-z]" file.txt
Performance Optimization
# Fixed string (faster)
grep -F "literal.string" large.txt
# Stop after first match
grep -m 1 "pattern" large.txt
# Binary file detection
grep -I "pattern" *
# Exclude large directories
grep --exclude-dir={node_modules,dist,.git} -r "pattern" .
# Parallel grep (with xargs)
find . -name "*.txt" | xargs -P 4 grep -l "pattern"
Notes
- Patterns: Use single quotes to prevent shell expansion
- Regex: Default is BRE (Basic Regular Expressions)
- Extended Regex: Use
-Eoregrepfor ERE - Perl Regex: Use
-Pfor PCRE (not always available) - Fixed String: Use
-Forfgrepfor literal strings (faster) - Case Sensitivity: Default is case-sensitive, use
-ito ignore - Recursion:
-rfollows symlinks,-Rdoesn't - Exit Status: 0 if match found, 1 if not found, 2 if error
- Multiple Files: Filename printed by default
- Color:
--color=autoonly colorizes terminal output - Context:
-A,-B,-Cfor showing surrounding lines - Invert:
-vinverts match (shows non-matching lines) - Count:
-ccounts matching lines, not occurrences - Only Matching:
-oprints only matched part - Line Numbers:
-nprefixes lines with line numbers - Whole Word:
-wmatches whole words only - Quiet:
-qsuppresses output, only returns exit status - Binary Files: Default is to print "Binary file matches"
- Encoding: Assumes UTF-8 by default
- Null Separator:
-Zfor use with xargs -0 - Alternatives: ripgrep (rg), ag (the silver searcher), ack
- Performance: Fixed string search is faster than regex
- Large Files: Consider using specialized tools for huge files
- Best Practices:
- Use
-Ffor literal strings (faster) - Use
--exclude-dirto skip large directories - Use
-lto just list files (faster) - Use
-mto stop after N matches - Quote patterns to prevent shell expansion
- Use
-qin scripts for boolean checks - Use
-rfor recursive directory search - Combine with
findfor complex file selection
Comments (0)
Add a Comment
No comments yet. Be the first to comment!