Sorting and removing duplicate lines
Quick answer
sort reorders text lines; uniq compares adjacent lines. Combine them to group repeated values and count occurrences. Knowing the difference prevents reports that accidentally miss duplicates.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/text-streams/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
sort normally uses locale-dependent text ordering; LC_ALL=C makes byte-order comparison predictable for these ASCII fixtures. sort -n compares leading numeric values instead of ordinary text order. uniq removes adjacent repeated lines; uniq -c prints a count for each adjacent group. sort | uniq -c works because equal lines become neighbors. sort -u is suitable for unique lines under the chosen comparison; sort -n -u may discard distinct lines with equal numeric keys. For sorted files, comm compares complete lines in three output columns (left only, right only, shared); join combines records with matching fields, normally requiring sorted join keys. Use the same locale and ordering for preparation and comparison.
For the sequence red, blue, red, uniq cannot combine the two red records because they are separated. Sorting puts equal records together, enabling uniq -c to count one group per distinct line. This also changes the original order; do not sort if preserving event chronology is the primary requirement.
Try the examples
The two red groups are separated by blue, so both remain.
Expected stdout:
redblueredCounts are left-padded by GNU uniq; the meaningful values are 1 and 3.
Expected stdout:
1 blue3 redNumeric order places 2 before 10, unlike ordinary C-locale lexicographic ordering.
Expected stdout:
21030Common mistakes
uniq alone is not a global deduplicator. Sorting changes record order, so do not sort an event log if chronology must be preserved. Never write sorted output back to the same input via >.
Practice
Run sort -u on labels.txt using LC_ALL=C and predict the two output labels. Explain when preserving original order would matter.
Related references
Study: sort, uniq, comm, join. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sorting and removing duplicates — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
Why can uniq leave repeated values?
Which command counts adjacent groups?
Which option orders numeric values?
Why set LC_ALL=C for this fixture?