Linux grep Command Examples

Practical grep snippets for searching text, filtering logs, and finding patterns in files.

Linux grep CLI
Basic Search
Search for a string in a file
grep "search_term" filename.txt
Basic grep usage. Returns all lines containing the search term.
Case-insensitive search
grep -i "search_term" filename.txt
Use -i to ignore case. Matches "Error", "error", "ERROR" etc.
Search recursively in directory
grep -r "search_term" /path/to/dir/
Use -r to search all files in a directory recursively.
Filter & Count
Count matching lines
grep -c "search_term" filename.txt
Returns the number of lines that match instead of the lines themselves.
Show line numbers
grep -n "search_term" filename.txt
Use -n to display line numbers alongside matching lines.
Invert match (exclude lines)
grep -v "search_term" filename.txt
Use -v to show lines that do NOT match the pattern.
Log Filtering
Filter ERROR logs
grep "ERROR" /var/log/app.log
Common use case: extract error lines from application logs.
Filter logs with context lines
grep -A 3 -B 3 "ERROR" /var/log/app.log
-A 3 shows 3 lines after the match. -B 3 shows 3 lines before. Useful for debugging.
Tail log and grep in real-time
tail -f /var/log/app.log | grep "ERROR"
Monitor a log file in real-time and filter for errors. Useful for live debugging.
Advanced Usage
Search with regex
grep -E "error|warn|fatal" filename.txt
Use -E for extended regex. This example matches lines with "error", "warn", or "fatal".
Search only filenames
grep -rl "search_term" /path/to/dir/
Use -l to list only filenames that contain the match, not the lines.
Exclude specific file types
grep -r "search_term" /path/ --exclude="*.log"
Exclude files matching a pattern. Use --include to do the opposite.