Lessons · Terminal · uniq -c: how many of each
How many of each
uniq -c prints each distinct line once with its count in front, right-aligned in a fixed width.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Most questions asked of a log are this shape.
How to think about it
sort | uniq -c, then sort -rn to rank.
Worked example
cut -d' ' -f2 access.log | sort | uniq -cEach endpoint with its count.
cut -d' ' -f2 access.log | sort | uniq -c | sort -rnRanked, biggest first. The -n matters: these are numbers.
printf '%s\n' a a b | uniq -d-d keeps only what repeated.
Your turn
Count how many of each line app.log holds.
sort app.log | uniq
Try it at a real prompt
The trap
The count is padded with spaces, so a later cut -d' ' -f1 sees an empty first field. awk '{print $1}' or sort -n cope; cut does not.
Practise uniq -c: how many of each on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.