grep
Overview
The grep
command searches input files for lines containing a match to a given pattern. It supports basic and extended regular expressions for pattern matching.
Syntax
grep [options] pattern [file...]
Common Options
Option | Description |
---|---|
-i |
Ignore case |
-v |
Invert match |
-n |
Show line numbers |
-l |
List matching files |
-c |
Count matches |
-r |
Recursive search |
-w |
Match whole words |
-x |
Match whole lines |
-E |
Extended regex |
-F |
Fixed strings |
-A n |
After context |
-B n |
Before context |
-C n |
Context lines |
Pattern Types
Type | Description |
---|---|
Basic | Simple patterns |
Extended | Advanced patterns |
Fixed | Literal strings |
Perl | Perl regex |
Key Use Cases
- Text search
- Pattern matching
- File filtering
- Log analysis
- Code search
Examples with Explanations
Example 1: Basic Search
grep "pattern" file
Search for pattern
Example 2: Recursive Search
grep -r "pattern" directory/
Search in directory
Example 3: Count Matches
grep -c "pattern" file
Count matching lines
Common Usage Patterns
Case insensitive:
grep -i "pattern" file
Multiple patterns:
grep -e "pat1" -e "pat2" file
Context lines:
grep -C 2 "pattern" file
Regular Expressions
- Character classes
- Anchors
- Quantifiers
- Alternation
- Grouping
Additional Resources
Best Practices
- Quote patterns
- Use context
- Check options
- Verify matches
- Document usage
Performance Tips
- Use fixed strings
- Limit recursion
- Exclude dirs
- Buffer size
- Parallel grep
Troubleshooting
- Pattern syntax
- File permissions
- Binary files
- Character encoding
- Memory usage