Back to roadmaps shell-script Course

Searching Logs with grep and Regular Expressions

grep is the go-to tool for searching text files and filtering output by pattern. It stands for Global Regular Expression Print.


1. Basic grep Syntax

# Search for "ERROR" string in a log file
grep "ERROR" /var/log/app.log

# Case-insensitive search
grep -i "error" /var/log/app.log

# Show 3 lines of context around each match
grep -C 3 "segfault" /var/log/syslog

2. Useful grep Flags

Flag Purpose
-i Case-insensitive matching
-n Show line numbers in the output
-r Recursively search all files in a directory
-l Only print filenames that contain the pattern
-v Invert match (print lines that do NOT match)
-c Print a count of matching lines
-E Use extended regular expressions

3. Practical Log Filtering Examples

# Find all HTTP 500 error responses in an Nginx access log
grep " 500 " /var/log/nginx/access.log

# Find lines that do not contain 200 status codes (find non-success requests)
grep -v " 200 " /var/log/nginx/access.log

# Count how many times a specific IP made requests
grep -c "192.168.1.1" /var/log/nginx/access.log

# Search for all error logs added in the past 5 minutes using extended regex
grep -E "2026-(06|07)-[0-9]+" /var/log/app.log | grep "CRITICAL"
Published on Last updated: