Bash

Count Occurrences of a Pattern

admin by @admin ADMIN
18h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Several ways to count matches: lines containing X, total matches across a file, matches grouped by capture, etc.
Bash
Raw
# Count lines matching pattern
grep -c "ERROR" /var/log/app.log

# Count total matches (not just lines — `-o` prints each match on its own line)
grep -o "ERROR" /var/log/app.log | wc -l

# Count files that contain at least one match (recursive)
grep -rlc "TODO" src/ | wc -l

# Top 10 error codes from an access log
grep -oE 'HTTP/1\.[01]" [0-9]+' access.log | awk '{print $2}' | sort | uniq -c | sort -rn | head

# Count distinct IPs hitting a 500
awk '$9 == 500 {print $1}' access.log | sort -u | wc -l
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.