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.
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.csvCommand:
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="xTE-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.txtCommand:
sort f.txt | uniq -c | sed 's/^ *//'Recorded output:
1 a
2 bExit 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.txtCommand:
cut -d, f.txtRecorded 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.
Source
Evidence
TE-23-A: uniq collapses adjacent duplicates only; cut is not a CSV parser
- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.
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