Summarize a log file with Tcl lists, dicts and regexp

8 steps · about 1 h 21 min · Beginner

  1. Open the log file for reading (reference, Tcl documentation, 6 min)

    Covers access modes and the channel you read from.

  2. Split the file contents into lines and fields (reference, Tcl documentation, 5 min)

    Turns one big string into a list you can loop over.

  3. Extract fields from each line with regexp (reference, Tcl documentation, 12 min)

    Shows match variables and -inline for pulling out sub-matches.

  4. Borrow working patterns for dates, IPs and words (article, Tcler's Wiki, 15 min)

    Real expressions you can adapt instead of writing from scratch.

  5. Count occurrences with dict incr (reference, Tcl documentation, 15 min)

    dict incr, dict for and dict get are all a tally needs.

  6. See idioms and pitfalls for dicts (article, Tcler's Wiki, 12 min)

    Community notes on nested dicts and when to prefer arrays.

  7. Sort the tally by count with lsort -stride (reference, Tcl documentation, 8 min)

    Sorts key-value pairs as units, highest count first.

  8. Print aligned report columns with format (reference, Tcl documentation, 8 min)

    Width and alignment specifiers give a tidy text table.