Puzzleshot #031 - Log pairing

raw data→cut→uniq→result

You have a log of order status updates, 10,000 lines, one per order:

2026-11-28 00:00:07 ORD-10001 shipped
2026-11-28 00:00:14 ORD-10002 returned
2026-11-28 00:00:21 ORD-10003 pending
2026-11-28 00:00:28 ORD-10004 shipped
...

You want to know how many orders are in each status, so you pull out the status column and count the duplicates:

cut -d' ' -f4 orders.log | uniq -c

You expected one line per status. Instead you get 5,851 lines, starting like this:

      1 shipped
      1 returned
      1 pending
      2 shipped
      1 returned
      1 pending
...

Two questions:

Bonus: is there a way to do it without sort at all?

Reveal solution

The short version: uniq only collapses identical lines that sit next to each other. It never looks anywhere else in the file, so every time the status changes, it starts a new count. Sort first, and every duplicate becomes a neighbor.

Round 1 - the fix:

cut -d' ' -f4 orders.log | sort | uniq -c
 
     991 cancelled
    2031 pending
    1031 returned
    5947 shipped

Four lines, one per status, and they add up to 10,000.

To rank them, sort the counts numerically, biggest first:

cut -d' ' -f4 orders.log | sort | uniq -c | sort -rn

Add | head -3 and you have a top 3.

Why 5,851 lines before? The statuses are mixed together in the order they happened. Every run of the same status got its own line, with the length of the run as its count. Add up all 5,851 counts and you still get 10,000, just chopped into pieces. The longest run in this file was 19 shipped in a row.

Round 2 - the awk way (the bonus):

awk '{c[$4]++} END {for (k in c) print c[k], k}' orders.log | sort -rn

awk keeps a counter for each status and adds one every time it sees it, so it reads the file once and never needs to sort the 10,000 lines. I still piped the result through sort -rn, because awk doesn’t guarantee any order when it prints the counters. In my test it gave the same four totals.

The trade-off: sort can spill to temporary files on disk, so sort | uniq -c copes with very large inputs. awk keeps its counters in memory, which is nothing for four statuses but grows with the number of different values. Counting millions of distinct IP addresses is a different story.

The things to consider:

Why does uniq work like this? It only compares each line with the one before it, so it can handle a stream without remembering anything. That’s why it expects sorted input.

When is plain uniq -c useful? When the runs matter, like how many times in a row the same line repeats.

What if you only want the distinct values, with no counts? sort -u.

How would you check your answer? The counts should add up to the number of lines in the file.

The takeaway:

uniq counts neighbors, not totals. Sort first.