Back to QuickRef
Grep
Text search and pattern matching utility for searching plain-text data sets for lines that match a regular expression.
Overview
Grep is a command-line utility for searching plain-text data sets for lines that match a regular expression. It’s one of the most powerful and frequently used tools in Unix/Linux systems.
Basic Usage
grep "pattern" filename
Example:
# Search for the word "error" in log file
grep "error" /var/log/system.log
Common Options
Case & Matching
-i
- Ignore case-v
- Invert match (exclude)-w
- Match whole words-x
- Match whole lines-F
- Fixed strings (no regex)-E
- Extended regex
Output Control
-n
- Show line numbers-c
- Count matches-l
- List matching files-L
- List non-matching files-o
- Show only matches-q
- Quiet mode
Context Options
# Show 3 lines after match
grep -A 3 "pattern" file
# Show 3 lines before match
grep -B 3 "pattern" file
# Show 3 lines around match
grep -C 3 "pattern" file
Regular Expressions
Basic Patterns
^
- Start of line$
- End of line.
- Any character*
- Zero or more+
- One or more (with -E)?
- Zero or one (with -E)
Character Classes
[abc]
- Any of a, b, c[^abc]
- Not a, b, c[a-z]
- Any lowercase[0-9]
- Any digit\d
- Digit (with -P)\w
- Word character (with -P)
Practical Examples
Search for IP addresses:
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" file.txt
Search for email addresses:
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" file.txt
Search in multiple files:
grep -r "TODO" /path/to/project
Search with file patterns:
grep -r --include="*.js" "console.log" .
Count occurrences:
grep -c "error" /var/log/system.log
Show only matching part:
grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" access.log
File Operations
Recursive Search
grep -r "pattern" /path
grep -R "pattern" /path
Include/Exclude Files
grep -r --include="*.txt" "pattern" .
grep -r --exclude="*.log" "pattern" .
Useful Combinations
Search for functions in code:
grep -n "function.*(" *.js
Find files containing pattern:
grep -l "pattern" *.txt
Search case-insensitive with line numbers:
grep -in "error" /var/log/system.log
Exclude binary files:
grep -I "pattern" *
Search for multiple patterns:
grep -E "error|warning|critical" /var/log/system.log
Exit Codes
- 0 - Match found
- 1 - No match found
- 2 - Error occurred
Tips and Tricks
- Use
grep --help
for complete option list - Combine with other tools:
ps aux | grep process_name
- Use aliases for common patterns:
alias finderr='grep -r "error" .'
- For complex patterns, consider using
egrep
(equivalent togrep -E
)
See Also
egrep
- Extended grepfgrep
- Fixed string greprg
(ripgrep) - Faster alternativeag
(the silver searcher) - Another fast alternative
Categories:
toolsLast updated: January 1, 2023