KKAIROS
Practical guideIllustrative3 min read

sort, uniq and cut: count things in a text file

sort orders lines, uniq collapses adjacent duplicates, cut extracts fields, characters or bytes. Tested here: sort then uniq -c counts each distinct line.

Published:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-23-A: uniq collapses adjacent duplicates only; cut is not a CSV parser

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'a\nb\na\n' > f.txt; printf '1,"x,y"\n' > c.csv

Command:

echo uniq=$(uniq f.txt | wc -l); echo sortu=$(sort f.txt | uniq | wc -l); echo cut=$(cut -d, -f2 c.csv)

Recorded output:

uniq=3
sortu=2
cut="x

TE-23-B: sort then uniq -c counts each distinct line

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'b\na\nb\n' > f.txt

Command:

sort f.txt | uniq -c | sed 's/^ *//'

Recorded output:

1 a
2 b

Exit status: 0. This status and the output match what was written before the run. This is the status of sed, the last command in the pipe.

TE-23-C: expected non-zero exit: cut with a delimiter but no field list is an error

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'a,b\n' > f.txt

Command:

cut -d, f.txt

Recorded output: none, standard output was empty.

Standard error from the same run:

cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.

Exit status: 1. This status and the output match what was written before the run.

TE-23-B: by the setup, f.txt holds the lines b, a and b. After sort, uniq -c printed 1 a and 2 b, with the leading spaces removed by sed. TE-23-C: cut -d, f.txt exited with status 1. The standard error holds cut: you must specify a list of bytes, characters, or fields, and a Try 'cut --help' line.

Limits

Locale affects order; -n for numbers; uniq needs sorted input; cut is not a CSV parser.

Ad

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-23-A | uniq collapses adjacent duplicates only; cut is not a CSV parser | 0 | PASS | b89df201f178 | | TE-23-B | sort then uniq -c counts each distinct line | 0 | PASS | b03bccf14bf8 | | TE-23-C | expected non-zero exit: cut with a delimiter but no field list is an error | 1 | PASS | fd1c19cf2519 |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides