grep Basics
You're debugging a production issue. There's a 500MB log file. You need to find all errors.
You could open it in a text editor and search. Or you could use grep and have the answer in 0.1 seconds.
What is grep?
grep searches text for patterns and prints matching lines.
The name comes from the ed editor command g/re/p - "globally search for regular expression and print."
Basic Usage
Every line containing "error" is printed.
Search Multiple Files
With multiple files, grep shows the filename before each match.
Recursive Search
Search all files in a directory tree:
Use -r Liberally
When you're not sure where something is, grep -r 'term' . searches the entire current directory tree.
Case-Insensitive Search
-i matches regardless of case.
Show Line Numbers
-n shows which line the match is on.
Count Matches
-c counts matching lines instead of printing them.
Invert Match
Find lines that DON'T match:
-v is incredibly useful for filtering out noise.
Only Print Filenames
-l lists files that contain the pattern, without showing the matches.
Opposite: -L lists files that DON'T contain the pattern.
Combining Flags
Flags can be combined:
-rni = recursive + line numbers + case-insensitive
Real-World Examples
Find Errors in Logs
Search Code for Functions
Check Config for Setting
How do you find all lines that do NOT contain 'DEBUG' in a log file?
Modern Alternative: ripgrep (rg)
ripgrep is a faster, more user-friendly grep replacement:
sudo apt install ripgrep # Then use: rg
ripgrep is:
- Faster - significantly faster on large codebases
- Smarter - ignores
.git,node_modulesby default - Prettier - colored output with context
For Interactive Use
Use rg for daily work - it's faster and has sensible defaults. Use grep in scripts for portability (grep is everywhere, rg might not be installed).
Quick Reference
| Flag | Effect |
|---|---|
-i | Case-insensitive |
-r | Recursive (search directories) |
-n | Show line numbers |
-c | Count matches |
-v | Invert (show non-matches) |
-l | List only filenames |
-L | List files without matches |
Key Takeaways
grep 'pattern' filesearches for text-ifor case-insensitive-rfor recursive directory search-nfor line numbers-vto invert (exclude matches)- Combine flags:
grep -rni 'term' .
Next: advanced grep with regex and more flags.