← All Exercises
Count Log Levels with awk and sort
basicbash
Background
Large log files are unreadable line by line. A quick severity histogram reveals the shape of an incident and is a common first triage step.
Problem
Given a log file with one record per line, count how many DEBUG, INFO, WARN, and ERROR entries it contains, ignoring lines that do not carry a bracketed level.
Input
A text file where each relevant line has a bracketed level as its second whitespace-separated field, for example a timestamp followed by [INFO].
Output
One line per present level in the form LEVEL count, sorted by count descending and then by level name ascending.
Sample tests
Sample 1
Input: 2026-10-01T09:00:00Z [INFO] started 2026-10-01T09:01:00Z [WARN] slow query 2026-10-01T09:02:00Z [ERROR] timeout 2026-10-01T09:03:00Z [INFO] finished
Expected: INFO 2 ERROR 1 WARN 1
Sample 2
Input: a file whose lines contain no bracketed level
Expected: no output
Your solution
Learning objective
Use awk associative arrays for grouping and GNU sort keys for a two-level ordering.