grep Command in Linux — 10 Practical Examples
The grep command is one of the most powerful tools in Linux. It searches text for patterns and is essential for developers, sysadmins, and anyone working with the command line.
Basic Syntax
grep [options] pattern [file...]10 Practical Examples
1. Search a file for a word
grep "error" server.logPrints every line in server.log containing “error”.
2. Case-insensitive search
grep -i "warning" server.logMatches “warning”, “Warning”, “WARNING”, etc.
3. Count matches
grep -c "404" access.logPrints only the number of matching lines, not the lines themselves.
4. Show line numbers
grep -n "TODO" main.pyOutput: 42: # TODO: add error handling — the line number is shown before each match.
5. Search recursively in all files
grep -r "function" src/Searches every file under the src/ directory.
6. Invert match (show lines that do NOT contain pattern)
grep -v "INFO" server.logUseful for filtering out noise — show only warnings and errors.
7. Show context lines around matches
grep -B 2 -A 3 "Exception" app.log-B 2→ 2 lines before the match-A 3→ 3 lines after the match
8. Search whole words only
grep -w "cat" words.txtMatches “cat” but not “catalog” or “catch”.
9. Use regular expressions
grep "^ERROR.*timeout" server.logLines starting with “ERROR” and containing “timeout” anywhere after.
10. Search for multiple patterns
grep -e "error" -e "warning" -e "critical" server.logMatches any line containing any of the three patterns.
Common Options Quick Reference
| Option | Meaning |
|---|---|
-i | Case-insensitive |
-r | Recursive |
-n | Show line numbers |
-c | Count matches |
-v | Invert match |
-w | Whole word match |
-l | List filenames only |
-B n | n lines before match |
-A n | n lines after match |
-C n | n lines around match |
Pro Tip: Search with rg (ripgrep)
If you find yourself using grep heavily, try ripgrep (rg). It’s faster, respects .gitignore, and has better defaults:
rg "TODO" --type pyInstall it with apt install ripgrep or brew install ripgrep.