Module 1 · Lesson 25 of 103

Buffering and the full toolkit

Explain stdout's buffering, write extended regular expressions, and build a text pipeline with cut, sort, uniq and tr to rank access-log data.

  • Beginner to advanced
  • 7 min read
  • 24 min lab
What you will need

Ubuntu 24.04 (WSL2, VM or container); a Raspberry Pi for the embedded sections

Your place in the module
By the end you can 4 objectives
  • Write basic and extended regular expressions using anchors, character classes, quantifiers and alternation.
  • Reshape text with cut, sort, uniq -c and tr, and explain why uniq needs sorted input.
  • Compose a pipe chain that reports the top client IPs and the 404 count from a web-server access log.
  • Explain why stdout is line-buffered on a terminal but fully buffered in a pipe while stderr is unbuffered.
Video coming soonBuffering and the full toolkit
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Pipes and basic grep
  • A pipe connects one process's stdout to the next's stdin; tee splits the stream to a file and onward.
  • grep matches regular expressions anywhere in a line, not whole words; -w and -E change that.
  • A pipe is a fixed-size kernel buffer that blocks the writer when full and delivers SIGPIPE when the reader is gone.
01

Buffering: why stdout lags stderr

3 min read

The previous lesson connected commands with pipes and covered grep's basic regular expressions. This lesson answers: why does stdout lag stderr, and how do extended regex and the text toolkit build a full pipeline?

Two layers sit between your program and the bytes on disk. The kernel moves data through file descriptors directly, but the C standard library adds its own buffer on top, and that buffer is the source of surprising ordering.

The library follows three rules. stdout is line buffered when it points at a terminal, meaning it flushes on every newline. stdout is fully buffered when it points at a pipe or a file, meaning it flushes only when its buffer fills or when the program exits. stderr is never buffered, so its bytes reach the device immediately.

The consequence shows up whenever you pipe a program that prints to both streams. stdout's output sits in the buffer while stderr's races straight through, so the error can appear before the result it belongs to:

bash
python3 -c "import sys; print('out'); print('err', file=sys.stderr)" 2>&1 | cat

Typical output (yours will differ) shows err before out, because the piped stdout was fully buffered while stderr flushed at once. On the terminal, with stdout line buffered, they appear in the written order. The same program, the same lines, a different order.

You can change the buffering without editing the program. stdbuf -oL forces line buffering, stdbuf -o0 forces no buffering, and python3 -u does the same for Python.

bash
stdbuf -oL cmd 2>&1 | cat

Run the earlier Python one-liner again with python3 -u (or set PYTHONUNBUFFERED=1) and the two lines come out in the written order even through the pipe. Note that stdbuf would not help here: it only changes the C library's stdio buffering, so it works for programs such as grep, cut and awk, while Python manages its own output buffers. The program did not change; only its buffering policy did, which is the point of the fix.

Going deeperWhy stderr is unbuffered by design

The C library sets stderr unbuffered so a diagnostic is seen even when the program crashes before flushing, since a buffered error could be lost with the process. The setvbuf call lets a program choose line, full or no buffering per stream, and stdbuf achieves the same from outside by preloading a library that overrides those choices. The reason the terminal gets line buffering while a pipe gets full buffering is an old performance trade-off: interactive output should feel immediate, while batch output benefits from fewer, larger writes.

Stream bufferingstdout toterminalstdout topipe/filestderrbufferingline bufferedfullybufferedunbufferedflushed whennewlinebuffer fullor exitimmediatelyso errors appearon each linelatefirst
How stdout and stderr are buffered differently on a terminal versus through a pipe.
02

Extended regular expressions

2 min read

The basic dialect forces a backslash before \|, \+, \?, \( and \{. The extended dialect, enabled with grep -E (or the old name egrep), makes those characters operators directly, which reads far better for real patterns.

bash
grep -E 'error|warn|fatal' app.log        # alternation
grep -E 'https?://' urls.txt              # s is optional
grep -E 'colou?r' text.txt                # color or colour
grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' log  # a date
grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}' log # an IPv4 shape

Each operator deserves a line. | means or, matching if either side fits. ? makes the previous item optional, + means one or more, and * means zero or more. {n,m} repeats the previous item between n and m times. Parentheses group items so an operator can apply to the whole group, as in the repeated octet pattern above. Anchors ^ and $ and classes like [0-9] work the same in both dialects.

One thing that trips people switching from other languages: POSIX extended regular expressions have no \d. The portable spelling for a digit is [0-9] or the POSIX class [[:digit:]], alongside [[:alpha:]], [[:alnum:]] and [[:space:]].

Try the extended operators below:

grep -E 'error|warn|fatal' prints the warn, error and fatal lines because | means or in the extended dialect; in basic grep the same | is literal, so the pattern matches nothing.

Both dialects match greedily: they take the longest string the pattern allows, from the leftmost position where a match can start. There is no lazy or non-greedy operator in POSIX regular expressions, so there is no way to ask for the shortest match; that idea belongs to Perl-style engines, which GNU grep offers only through -P. Anchoring both ends turns a loose search into an exact check, so grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}$' accepts nothing but a bare IPv4 address with no surrounding text.

BusyBox grep is a subset

On an embedded root filesystem, grep is usually the BusyBox applet. It supports -E and -F but not -P, and its extended dialect is a subset of GNU's. Test a pattern on the target board, not just on your workstation, because an option that works in GNU grep may be absent on the device.

Basic vs extended regexBRE (grep)ERE (grep -E)alternation\||grouping\( \)( )plus andoptional\+ \?+ ?repeat count\{n,m\}{n,m}
The same operators spelled in the basic and extended dialects side by side.
03

The text toolkit and the full pipeline

4 min read

cut extracts columns. -d sets the delimiter and -f selects fields, while -c selects character positions.

bash
cut -d: -f1 /etc/passwd      # every username
cut -c1-10 access.log        # the first ten characters

sort orders lines, with -n for numeric order, -r to reverse and -k to pick a key. uniq collapses adjacent duplicates, and -c prefixes each with a count. Because uniq only compares neighbours, you sort first. sort -u removes duplicates outright during sorting, a shortcut when you only want distinct values; reach for uniq -c when the count itself is the point.

bash
sort words.txt | uniq -c     # count each distinct word
sort -rn sizes.txt           # largest first

tr translates, deletes or squeezes characters. It maps characters positionally, so tr 'A-Z' 'a-z' lowercases.

bash
echo 'HELLO' | tr 'A-Z' 'a-z'      # hello
tr -d '\r' < windows.txt           # strip carriage returns
tr -s ' ' < messy.txt              # collapse runs of spaces

xargs turns lines of stdin into arguments for another command. It is how a pipeline feeds a command that reads arguments, not stdin, and it splits the list into batches that fit within the kernel's command-line length limit.

bash
grep -l 'TODO' *.c | xargs grep -n 'TODO'
find . -name '*.log' -print0 | xargs -0 grep -l error

-n bounds how many arguments each invocation receives, and -I{} substitutes a name at a fixed position, which matters when the argument must appear twice:

bash
seq 1 20 | xargs -n 5 echo         # five arguments per echo
echo report | xargs -I{} cp {} {}.bak

The kernel caps the size of a single command line, reported by getconf ARG_MAX. xargs respects it by splitting the input into batches, which is why grep TODO *.c over tens of thousands of files fails with argument list too long. Note that the glob is expanded by the shell before any command runs, so you cannot rescue it by piping its result into xargs; generate the names without one giant command line instead, with find . -name '*.c' -print0 | xargs -0 grep TODO or the bash builtin printf '%s' *.c | xargs -0 grep TODO (a builtin is not subject to the limit).

The -print0 and -0 pair uses a NUL byte as the separator, which survives filenames containing spaces. Now the pieces combine into the log-analysis pipeline.

1extract one field

cut -d' ' -f1 access.log takes the first space-separated field of each line, the client IP.

2group the duplicates

sort puts identical IPs next to each other, so uniq -c can count them in one pass.

3rank and trim

sort -rn orders by count descending, and head keeps the top few.

bash
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head
grep -c ' 404 ' access.log

Watch each stage transform the sample below:

cut -d' ' -f1 extracts each client IP, sort makes duplicates adjacent, uniq collapses them, and head keeps the first three lines. The real top-IP ranking adds uniq -c to count and sort -rn to order by count, which this simulation does not implement.

The spaces around 404 stop the pattern matching 1404 or 4040. A real access log has spaces inside the quoted request line, which is why cut on a later field produces empty columns; field extraction that ignores whitespace runs is the job of awk, which the next lesson covers.

Streaming beats loading on small boards

A board with 512 MB of RAM cannot slurp a multi-gigabyte log. The pipeline above streams line by line: only sort spills to disk when the input outgrows memory. Use sort -S to bound its memory or sort -T to point its temporary files at larger storage.

The same mistakes recur, and each has a symptom, a cause and a fix.

Symptom Cause Fix
Error still prints after cmd > f > redirects stdout only cmd > f 2>&1 or &> f
f is empty after cmd 2>&1 > f duplicate ran before stdout moved cmd > f 2>&1
> f wiped a file you meant to extend > truncates use >>
uniq -c splits one value into several duplicates were not adjacent sort | uniq -c
grep word matches noerror too grep matches patterns, not words grep -w word
grep 'a|b' matches nothing | is alternation only in -E grep -E 'a|b'
cut -d' ' -f2 gives empty fields every space is a delimiter use awk, or tr -s ' ' first
The log-analysis pipelinecut -f1IP columnsortgroupduplicatesuniq -ccount eachsort -rnrank bycountheadtop Ncut -f1IP columnsortgroupduplicatesuniq -ccount eachsort -rnrank bycountheadtop N
The full log pipeline: cut, sort, uniq -c, sort -rn and head.
Rank the top client IPs
192.0.2.99
198.51.100.23
203.0.113.50
203.0.113.7
203.0.113.7
203.0.113.7
learner@embeddex:~/lab$ # uniq -c counts each run of adjacent duplicates
learner@embeddex:~/lab$ cut -d' ' -f1 access.log | sort | uniq -c
      1 192.0.2.44
      1 192.0.2.99
      1 198.51.100.23
      1 203.0.113.50
      3 203.0.113.7
learner@embeddex:~/lab$ # sort -rn ranks by count, head keeps the top
learner@embeddex:~/lab$ cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head
      3 203.0.113.7
      1 203.0.113.50
      1 198.51.100.23
      1 192.0.2.99
      1 192.0.2.44
learner@embeddex:~/lab$ # the spaces around 404 stop it matching 1404 or 4040
learner@embeddex:~/lab$ grep -c ' 404 ' access.log
1
04

Try it

1 min read

Open the lab for this session and run it in a scratch directory. Generate a small access log, then build the reports from this lesson: the top client IPs with cut -d' ' -f1 | sort | uniq -c | sort -rn | head, the 404 count with grep -c ' 404 ', and a redirection exercise that captures stdout and stderr separately with > f 2>&1. Then run the same pipeline over SSH on your Raspberry Pi and compare the BusyBox tools' options with the GNU versions. The practice pack adds predict-the-output drills for redirection order and buffering.

Key takeaways

  • sort before uniq -c, because uniq only collapses adjacent identical lines.
  • stdout is line-buffered on a terminal but fully buffered in a pipe; stderr is never buffered.
  • In grep -E, +, ?, |, ( and { are operators without backslashes, and POSIX ERE has no \d, so a digit is [0-9] or [[:digit:]].
  • A pipeline streams line by line, so a memory-limited board can analyze a log larger than RAM; only sort spills to disk.
Reflect
  1. Explain to a colleague, in two sentences: write basic and extended regular expressions using anchors, character classes, quantifiers and alternation.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close