Searching Text (grep)
The grep command searches for patterns in files. It's one of the most powerful and frequently used commands in Linux.
Basic Usage
grep "pattern" filename
What grep Does
grep stands for "Global Regular Expression Print". It:
- Searches for patterns in files
- Prints matching lines
- Supports regular expressions
Common Options
| Option | Description |
|---|---|
-i | Case insensitive |
-n | Show line numbers |
-c | Count matches |
-v | Invert (show non-matching) |
-r | Recursive (search directories) |
-l | List filenames only |
Case Insensitive Search
grep -i "error" logfile.txt
Recursive Search
Search all files in directory:
grep -r "TODO" ./
grep -r "function" --include="*.js" ./
Exercise: Search for Text
Search for "Learn" in the notes file:
Line Numbers and Context
grep -n "error" file.txt # Show line numbers
grep -C 2 "error" file.txt # 2 lines context
grep -B 2 "error" file.txt # 2 lines before
grep -A 2 "error" file.txt # 2 lines after
Count Matches
grep -c "error" logfile.txt # Number of matching lines
grep -c "TODO" *.py # Count in each file
Inverse Match
Show lines that DON'T match:
grep -v "debug" logfile.txt
Multiple Patterns
grep -E "error|warning" log.txt # OR
grep "error" file.txt | grep "critical" # AND
Regular Expressions
grep supports regex patterns:
grep "^Start" file.txt # Lines starting with "Start"
grep "end$" file.txt # Lines ending with "end"
grep "colou?r" file.txt # "color" or "colour"
grep "[0-9]{3}" file.txt # Three digit numbers
Real-World Examples
Find Errors in Logs
grep -i "error" /var/log/syslog
grep "ERROR\|WARN" app.log
Search Code
grep -r "function" --include="*.js" src/
grep -rn "TODO" --include="*.py" ./
Filter Process List
ps aux | grep nginx
Exercise: Count Matches
Count how many lines contain "session" in /var/log/auth.log:
Key Takeaways
grepsearches for patterns in files- Use
-ifor case insensitive - Use
-rfor recursive directory search - Use
-nto show line numbers - Combine with pipes for powerful filtering

