NASutils Knowledge BaseUnofficialPolski

Bash · lesson 26 of 30 · Tools for the NASSummarise a log

awk counts by day and level in one pass.

Programming on the NAS › Bash in 30 lessons

26-log-summary.sh Download 26-log-summary.sh

#!/usr/app/TurboShell/bin/bash
# One line per day: how many lines of each level
set -euo pipefail
awk '
  NF > 2 { count[$1, $3]++; days[$1] = 1 }
  END {
    for (d in days)
      printf "%s  info %d  warn %d  error %d\n", d, count[d, "INFO"], count[d, "WARN"], count[d, "ERROR"]
  }' "${1:-nas.log}" | sort

echo "The errors:"
awk '$3 == "ERROR" { day = $1; time = $2; $1 = $2 = $3 = ""; sub(/^ +/, ""); print "  " day, time, $0 }' "${1:-nas.log}"

Terminal

$ bash 26-log-summary.sh
2027-01-04  info 2  warn 1  error 1
2027-01-05  info 2  warn 1  error 1
2027-01-06  info 2  warn 1  error 1
The errors:
  2027-01-04 09:02:44 share Documents is full
  2027-01-05 02:03:10 backup stopped: no space
  2027-01-06 18:09:33 disk 3 read error

Exercise

Add a line with the totals.