TT Lab
Blog Get started
Learn Learning paths Courses

Linux Fundamentals

Pipes Join Small Programs Into a Sentence

Continue in TT Lab

In one sentence

grep selects, sed edits, and awk counts. Connect these three tools with pipes, and five lines are enough to extract an answer from hundreds of thousands of log lines.

Why this matters

You get an incident report: "Responses have been slow since 3 p.m." The log has 400,000 lines, and just opening it in an editor takes a few seconds. What you need here is not a log viewer but the ability to turn a question into a command.

All three questions have the same shape. So you only need to memorize one idiom.

... | sort | uniq -c | sort -rn | head

uniq -c counts only adjacent duplicates, so sort in front is essential, and the sort -rn at the end sorts by count in descending order. These four pieces are the standard answer to the question "what is the most frequent?"

How it works

The criteria for choosing a tool are simple. If you only select lines, use grep; if you edit lines, use sed; if you work with fields or calculate, use awk. Using a tool stronger than you need makes things slower and harder to read.

You should also know what a pipe really is. Each command connected by pipes runs in a separate process at the same time, and the stdout of the earlier one is connected to the stdin of the later one. Two properties follow from this.

  1. Even a large file is processed as a stream without loading all of it into memory. That is why 400,000 lines are fast.
  2. A variable changed inside a pipeline does not remain outside it, because it runs in a subshell.

And the exit code of a pipeline is, by default, that of the last command. In curl ... | jq ... | wc -l, even if curl fails, if wc prints 0 the whole thing looks like a success. The mechanism that prevents this trap in scripts is set -o pipefail, which we cover in detail in the next course.

It is a good idea to fix a few performance anti-patterns now.

Instead of this Write this
`cat f grep p`
`sort uniq`
`cat f wc -l`
`echo "$s" cut -d. -f1`

What you see in the field

First, aggregating status codes. One line, awk '$9 ~ /^5[0-9][0-9]$/ {print $7}' access.log | sort | uniq -c | sort -rn | head -10, gives you the ten paths that returned the most 5xx. Type this before you open a dashboard.

Second, do ratio calculations with awk. Counts alone are often not enough to judge. If you calculate everything at once in the END block, as in awk '{t++; if ($5 != 200) e++} END {printf "%.1f\n", e*100/t}', you do not need to read the file twice.

Third, do not read the log from the beginning. The first move is to cut out only the five minutes before and after the time of the incident. The habit of scanning all 400,000 lines not only eats time; on a disk whose I/O is already saturated, the diagnosis itself makes the incident worse.

Habits with a large file

When logs reach tens of gigabytes, reducing how much you read matters far more than which tool you choose. Just a few habits can turn a command that takes minutes into one that takes seconds.

Cut first. Narrowing the range by time is the first move. If the log is sorted by time, extract only the interval with something like sed -n '/03:00/,/03:10/p', or pick only the file for that time range in the first place. And if you are sure what you are looking for, stop at the first match with grep -m 1. There is no reason to read all 400,000 lines to the end.

Take out only the columns you need. If you narrow the fields first, as in awk '{print $7}', the data the following sort handles becomes much smaller. sort is the most expensive spot in a pipeline, so reducing data before it has the biggest effect.

Check whether sorting is really needed. If you only need to count, you can count in one pass with an awk associative array. awk '{c[$7]++} END {for (k in c) print c[k], k}' | sort -rn | head does not sort everything and sorts only the result at the end, so it is much faster when there are many lines and few distinct values.

Turn off the locale. Putting LC_ALL=C in front makes sort and grep switch their character comparison rules to simple byte comparison, which is noticeably faster. However, the sort order changes, so be careful with results you show to people.

And read compressed logs as they are, without decompressing them. With zgrep and zcat you do not need to create temporary files on disk, and you avoid the accident of filling up the remaining space while diagnosing on a disk that is already full. Making sure the diagnosis does not make the incident worse is basic courtesy when working on a large system.

When the number differs from yesterday: pipelines fail silently

When you get a report that a report's numbers disagree with the dashboard, you will want to rewrite the script from scratch. What to do before that is to see whether the number came out smaller or larger. If it undercounted, there is a place it did not read; if it overcounted, it counted something it should not have. This one question cuts the candidates in half.

The most common culprit for undercounting is log rotation. If a log that used to rotate once a day at midnight switches to size-based rotation, yesterday gets split across the tail of access.log, .1, and the compressed .2.gz. A script written on the assumption "yesterday = yesterday's single file" is right until last week and then silently goes wrong from that day on. Just looking at the file list and the timestamps of each file's first and last lines shows right away where the day got scattered. When fixing it, do not list specific file names; make it read all the rotated files, so it holds up even if the rotation settings change again. zcat -f, which streams compressed and plain files alike, fits here.

When columns shift, you can undercount or overcount. If one more node starts writing logs and that node pads columns with several spaces, cut -d' ', which splits on a single space, looks at the wrong column on those lines. awk treats consecutive spaces as a single boundary, so it splits the same lines correctly. If you hear "we added nodes this week", this cause is worth suspecting first.

When it overcounts, suspect substring matches. grep 404 matches if 404 appears anywhere in the line; it also counts /img/404.png or order number 1404 as a 404 response. To count status codes, compare only the status code column.

When the top item changes, suspect sorting. As you saw earlier, uniq -c groups only identical lines that are adjacent. Used without sorting, the top item becomes not "the value that is most frequent overall" but "the value that came out in the longest single run". It is roughly right most days and wrong only on days when a particular path bunches up.

All four share a common check: pull a few lines the script counted as "yes" and a few it discarded as "no", and compare them by eye. Comparing only numbers never shows you why it was wrong. And after fixing it, run it once more on a different day's log; that is the only confirmation that the calculation is right, rather than tuned to today's number.

What you will do in the next lab

Using /opt/lab/data/app.log as your material, you extract the error count, the IP with the most requests, the 500 responses, the unique paths, counts by status code, and the top paths in turn, and you build a summary report script that also computes the error rate. The last two steps raise incidents: you fix a daily count that missed rotated logs, and you tell apart and fix three report scripts that are wrong for different reasons.