Count Unique Values in a Stream

Intermediate Bash Foundations Bash sort uniq Pipelines Aggregation
Significance:

The sort | uniq -c | sort -rn idiom is one of the most useful three-command pipelines
in existence. Bioinformaticians use it constantly: counting reads per chromosome from a SAM file,
tallying variant types in a VCF, summarising species in a metagenomic classification. It also
demonstrates why pipes matter — each tool does one thing, and their composition does something none of
them could alone.

Statement

A list of values arrives on standard input, one per line.

Count how many times each distinct value appears, and print the results sorted by count descending. Where
counts tie, sort by value ascending lexicographically.

Print each result as <count> <value> separated by a single space, one per line.

Input — read from standard input
Variable Type Description
values
line 1..n
str One value per line
1 <= lines <= 5000, values contain no whitespace

These variables are already read for you in the starter code on the right.

Output

str one line per distinct value as count then value, sorted by count descending then value ascending

Sample Cases
Sample 1
Input
chr1
chr2
chr1
chr3
chr1
chr2
Expected Output
3 chr1
2 chr2
1 chr3
chr1 appears three times, chr2 twice and chr3 once, giving a descending count order.
Sample 2
Input
SNP
INDEL
SNP
Expected Output
2 SNP
1 INDEL
Two distinct variant types, one appearing twice.

Submit also runs your code against 3 hidden test cases. Hidden inputs are never shown — if one fails you'll get its number and a description of the mismatch, not the data.

Constraints
  • Values contain no spaces or tabs
  • Output separator is a single space, not a tab or padded columns
  • Ties in count are broken by value ascending, which makes output deterministic
  • Blank lines in the input are ignored
Further Reading
  • uniq -c requires its input to be sorted first, or repeated values in different places are counted
    separately.
  • uniq -c pads its counts with leading spaces — awk '{print $1, $2}' normalises the spacing.
  • Sorting by two keys at once: sort -k1,1nr -k2,2 gives numeric descending on the count and
    lexicographic ascending on the value.

Judged against GNU Bash 5.1.0.


My Notes
Log in to save personal notes.
Console output will appear here when you click Run Code or Submit...
Expected: values — the whole input (One value per line)
Next Problem
Transcribe DNA to RNA with tr