Sort, count and aggregate text
sort orders text lines according to locale and selected keys; LC_ALL=C gives reproducible byte-oriented ordering in these ASCII fixtures. -n compares numeric values; -t and -k select a field separator and key. uniq compares adjacent records, not all records globally, so sort before uniq -c when counting identical labels. wc -l counts newline bytes, not necessarily logical records; wc -c counts bytes and wc -m counts characters according to locale. Pipelines combine distinct tools; consider pipefail when failure propagation matters. For human-language text, choose the intended locale rather than always forcing C. Numeric keys compare equal numeric values even if their text differs; GNU sort can use the whole line as a final tie-breaker unless -s is used. The examples use simple decimal integers and fixed ASCII text.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Count repeated labels
printf '%s\n' red blue red green blue red | LC_ALL=C sort | uniq -cExpected stdout:
2 blue1 green3 redGNU uniq pads counts in this environment. Sorting brings identical labels together.
Sort a numeric field
printf '%s\n' 'job:10' 'task:2' 'note:1' | LC_ALL=C sort -t ':' -k2,2nExpected stdout:
note:1task:2job:10The key is exactly the second field, sorted numerically.
Count newline bytes
printf 'a\nb' > records.txt || exit 1wc -l < records.txt || exit 1wc -c < records.txtExpected stdout:
13There is one newline byte and three total bytes, although a human sees two records.
Common mistakes
uniq alone misses separated duplicates. Lexical ordering puts 10 before 2; numeric sorting is different. wc -l does not count a final unterminated record.
Practice
Generate labels red, blue, red, green, blue, red. Count each label, then sort the counts numerically. Predict the output and explain the role of each command.
Next: Transform text with sed and awk