cut, sort, uniq and tr Pipelines

cut, sort, uniq and tr Pipelines in Bash: --- A materials recovery facility is where a mixed truckload of recycling becomes neat bales of single materials.


The Analogy: The Recycling Sorting Line

A materials recovery facility is where a mixed truckload of recycling becomes neat bales of single materials. The waste never sits in one machine that "does recycling"; instead it travels down a long conveyor past a row of stations, each of which performs exactly one narrow job and hands the stream on to the next. A trommel screen takes only a size fraction; an overband magnet lifts out the steel; an air classifier blows the light plastics one way and the heavy glass another. No single machine is clever. The cleverness is in the order they are bolted together.

The first station is a slicer: it takes each item and keeps only the part that matters, discarding the rest. That is cut -- from every line it keeps just the columns you name and throws the others away. Downstream, the separators bring like next to like: all the aluminium together, all the cardboard together. That is sort -- it does not remove anything, it just arranges the stream so that identical things become neighbours. The whole plant depends on this grouping happening before anything tries to act on runs of identical material.

Near the end sits the baler and its counter. It watches the stream go by and, whenever it sees a run of identical items, it compresses them into one bale and stamps the count on the side: "412 aluminium cans". That is uniq -- it collapses adjacent identical lines into one, and with a flag it writes the tally. There is also a wash station that scrubs and standardises every item regardless of type -- stripping labels, rinsing residue -- so that two cans that should match actually do. That is tr, translating or deleting characters uniformly across the whole stream.

The plant has one unforgiving rule, and every new operator learns it the hard way. The baler only recognises a run when identical items are already adjacent. If someone wires the baler in before the separators, the stream is still mixed: a can, a bottle, a can, a box, a can. The baler sees no runs longer than one, bales each item on its own, and stamps "1" on everything -- so the daily report claims one can, one bottle, one can, one box, one can, wildly undercounting the cans that were never brought together. The order of stations is not a convenience; it is the difference between a true tally and confident nonsense. And the very last station, a picker that keeps only the top few bales for the showroom, will quietly leave behind a bale exactly as large as one it kept, if it stops counting at a fixed number.


Syntax or Core Structure

These four tools are filters: each reads standard input, transforms it, and writes standard output, so they chain with pipes into a processing line. cut is the slicer. With -d you name the delimiter and with -f the fields to keep:

# visits.csv: user,path,status
alice,/home,200
bob,/login,200
alice,/home,200
carol,/api,500
bob,/home,200
alice,/api,500
cut -d, -f1 visits.csv

Output:

alice
bob
alice
carol
bob
alice

-d, sets the delimiter to a comma and -f1 keeps the first field, so this extracts the user column. You can keep several fields at once with a list: cut -d, -f1,3 yields alice,200, bob,200, and so on, preserving the delimiter between them. cut can also slice by character position with -c; echo 'ABCDEFGH' | cut -c1-3 prints ABC. It only ever removes; it never reorders or combines, which is why it is almost always the first station on the line.


Technical Depth: Sorting, Deduplicating and Translating

Slicing by character position

Not every file is delimited. Fixed-width records -- dates, codes, formatted reports -- put each field at a known column, and cut -c slices by character position rather than by field. A range keeps a span, and a comma-separated list keeps individual columns:

echo '2026-09-23' | cut -c1-4    # the year
echo '2026-09-23' | cut -c6-7    # the month
echo '2026-09-23' | cut -c9-     # day to end of line

Output:

2026
09
23

-c1-4 keeps characters one through four, -c6-7 the two month digits, and -c9- everything from the ninth character onward. Use -c when the layout is by column and -f when it is by delimiter; mixing them up is the first thing to check when cut returns the wrong slice.

sort arranges the stream

sort reorders lines. By default it sorts lexically -- character by character -- which is wrong for numbers, where -n gives numeric order. -r reverses, -t sets a delimiter, and -k picks the field to sort on. To order the visit log by its numeric status field:

sort -t, -k3 -n visits.csv

Output:

alice,/home,200
alice,/home,200
bob,/home,200
bob,/login,200
alice,/api,500
carol,/api,500

-t, splits on commas, -k3 sorts on the third field, and -n compares it as a number so 200 sorts before 500 rather than by first digit. These are the flags you will use most:

FlagEffect
-nCompare as numbers, not text
-rReverse the order
-t CUse C as the field delimiter
-k NSort on field number N
-uOutput only the first of each equal run

uniq collapses adjacent duplicates

uniq removes repeated lines, but only when they are next to each other, and -c prefixes each surviving line with its count. This is why sort almost always comes first. Watch what happens without it, on the path column whose values are scattered:

cut -d, -f2 visits.csv | uniq -c

Output:

      1 /home
      1 /login
      1 /home
      1 /api
      1 /home
      1 /api

Every count is 1, because no two identical paths happen to be adjacent -- the baler wired in before the separator. Sort first and the runs form, so the counts become real:

cut -d, -f2 visits.csv | sort | uniq -c

Output:

      2 /api
      3 /home
      1 /login

Now /home is correctly counted three times. The rule is absolute: uniq sees only neighbours, so feed it sorted input whenever you want true totals.

Finding duplicates and singletons

Beyond counting, uniq can filter by repetition. -d keeps only lines that were duplicated; -u keeps only lines that appeared exactly once. Both still require sorted input:

cut -d, -f1 visits.csv | sort | uniq -d

Output:

alice
bob
cut -d, -f1 visits.csv | sort | uniq -u

Output:

carol

alice and bob each appear more than once, so -d lists them; carol appears a single time, so -u lists only her. Together they partition the sorted stream into repeats and singletons. This table collects uniq's common flags:

FlagEffect
-cPrefix each line with its occurrence count
-dPrint only lines that are repeated
-uPrint only lines that occur exactly once
-iCompare lines case-insensitively

sort -u and counting distinct values

When you want the distinct lines and no counts, sort -u does the grouping and the collapse in one step, equivalent to sort | uniq but shorter:

cut -d, -f2 visits.csv | sort -u

Output:

/api
/home
/login

Piping that into wc -l answers "how many distinct paths were visited?" in a single line: cut -d, -f2 visits.csv | sort -u | wc -l prints 3. Counting distinct values this way -- slice a column, sort unique, count lines -- is one of the most reached-for one-liners in day-to-day log work, and it composes from the same filters without a single variable.

tr translates and deletes characters

tr maps one set of characters to another across the whole stream, or deletes them. It works on characters, not fields or lines:

echo 'alice' | tr 'a-z' 'A-Z'      # upper-case
echo 'a,,b,,c' | tr -s ','          # squeeze repeats
echo 'hello123world' | tr -d '0-9'  # delete digits

Output:

ALICE
a,b,c
helloworld

tr 'a-z' 'A-Z' translates each lower-case letter to its upper-case partner, -s squeezes each run of the given character down to one, and -d deletes the given characters entirely. Because it standardises the stream uniformly, tr is the wash station: it makes items that should match actually match before they reach sort and uniq.

OptionEffect
tr X YTranslate each character in set X to the matching one in Y
-dDelete every character in the given set
-sSqueeze each run of a repeated character down to one
-cComplement the set, i.e. act on characters not listed

The -c flag earns its keep when paired with -d: the combination -cd reads as "delete every character that is not in this set", which is the tidy way to keep only the characters you want rather than listing every one you do not. Pulling the digits out of a messy field becomes a single filter:

echo 'phone: 555-1234' | tr -cd '0-9'

Output:

5551234

That reads as "complement of 0-9, then delete", so every letter, space, colon and dash is stripped and only the seven digits survive. Reaching for -cd instead of enumerating the unwanted characters keeps the command short and keeps it working when the input contains punctuation you did not anticipate.


Real World Example: Top Requested Paths

A common first question about any access log is "what are the most-requested URLs?" The whole answer is one pipeline: slice out the path column, group identical paths together, count each run, order the counts high to low, and keep the top few. This top_paths.sh wraps exactly that line, with the file and the cut-off as arguments.

#!/usr/bin/env bash
# top_paths.sh -- the most-requested paths in a visit log
set -euo pipefail

FILE="${1:-visits.csv}"
N="${2:-3}"

cut -d, -f2 "$FILE" | sort | uniq -c | sort -rn | head -n "$N"

Running bash top_paths.sh prints:

Output:

      3 /home
      2 /api
      1 /login

Read the pipeline left to right as five stations. cut -d, -f2 keeps only the path column. sort brings identical paths next to each other. uniq -c collapses each run to one line stamped with its count. sort -rn reorders those counted lines by the number, reversed, so the busiest path rises to the top. head -n "$N" keeps the first N lines. Each tool is trivial alone; composed, they answer a real question in a single readable line with no temporary files and no loop.

The design is idiomatic Unix: every stage is a standard filter, so the same shape solves a hundred variants. Swap -f2 for -f1 and it becomes top users; change the delimiter and it reads a different log; drop head and it is a full frequency table. The pipeline streams, so it handles a log far larger than memory, and each stage is independently testable by cutting the pipe at any |.

The script has a real flaw that only shows at the cut-off. head -n "$N" stops after a fixed number of lines, but counts can tie. Give it a log where /home occurs three times and both /api and /login occur twice, and top_paths.sh log 2 prints /home and just one of the two paths tied at two, silently hiding the other equally-frequent path behind the boundary. Which one survives depends on how sort breaks the tie, not on anything meaningful. A report that must be honest about ties should detect a tie straddling the cut-off and either include all tied entries or mark that more exist, rather than trusting head to draw a fair line through equal values.


Common Mistakes

  1. Running uniq without sorting first. uniq collapses only adjacent duplicates, so on unsorted input it undercounts, stamping 1 on values that recur later. Always sort | uniq unless you truly want to find only consecutive repeats.
  1. Sorting numbers lexically. Plain sort puts 10 before 9 because it compares text left to right. Use -n for any numeric column, or the "top" of your report will be wrong.
  1. Forgetting cut's default delimiter is a tab. cut -f1 on space-separated data returns the whole line, because the fields were never split. Pass -d' ' for spaces, and remember cut treats each delimiter separately.
  1. Expecting cut to collapse repeated delimiters. Unlike awk, cut does not merge runs of spaces, so two spaces create an empty field. For ragged whitespace, awk is the better splitter.
  1. Thinking tr replaces strings. tr 'abc' 'xyz' maps a to x, b to y, and c to z character by character; it does not turn the word abc into xyz. For string replacement use sed.
  1. Trusting sort -rn to break ties meaningfully. When counts tie, the secondary order comes from comparing whole lines, not from anything you chose. Add an explicit key or accept that tied rows have no intended order.
  1. Letting locale change the sort. Sorting order and case-folding depend on the locale, so results differ between machines. Prefix with LC_ALL=C for stable, byte-order sorting in scripts.
  1. Parsing uniq -c output naively. Its count field is right-justified with leading spaces, so a naive split on the first character or a fixed column can misread it. Trim or split on whitespace.
  1. Cutting a top-N list with head across a tie. head -n N stops at a fixed line, hiding entries equal to the last one kept. A faithful top-N must handle a tie sitting on the boundary.

Best Practices

  • Always sort before uniq. Grouping identical lines is what makes uniq's collapse and count correct; the two are almost always used together.
  • Force numeric sorting for numbers. Use -n (and -k to pick the field) so counts and amounts order by value rather than by leading digit.
  • Pin the locale for reproducibility. LC_ALL=C sort gives the same byte-order result on every machine, which matters for scripts and tests.
  • Match cut's delimiter to the data. Set -d explicitly and recall the default is a tab; for ragged whitespace reach for awk instead.
  • Use tr for character-level work only. Case-folding, deleting, and squeezing characters are its strengths; leave string and pattern replacement to sed.
  • Build pipelines one stage at a time. Add a | stage, check the output, then add the next; each filter is independently inspectable, which makes debugging trivial.
  • Choose a delimiter that cannot appear in a field. If a value may contain your separator, either quote-aware tooling or a safer delimiter such as a tab avoids silent mis-splitting.
  • Handle ties in top-N reports explicitly. Detect counts equal to the cut-off value and include them, or state that more entries share that count, rather than letting head decide.

Practice Exercises

  1. Top users. Adapt top_paths.sh to report the most active users instead of paths by changing only the cut field. Verify the counts against visits.csv by hand.
  1. Prove the ordering rule. Take the path column and run it through uniq -c with and without a preceding sort. Show the counts that differ and explain, in one sentence, why the unsorted version undercounts.
  1. Numeric versus lexical. Create a file of the numbers 2, 10, and 9, one per line. Sort it with sort and with sort -n and record the difference. State which is correct for counts.
  1. Expose the tie flaw. Build a small log where two paths tie for second place, run top_paths.sh log 2, and show that one tied path is hidden. Describe how you would change the script to report ties honestly.