tl;dr sort myfile.log | uniq -c | sort -n -r

I wanted to count recurring lines in a log file and started writing a complicated Python script but then wondered if I can just do it with bash basics.
And after some poking and experimenting I found a really simple one-liner that I'm going to try to remember for next time:

You can't argue with the nice results :)

cat myfile.log
one
two
three
one
two
one
once
one

▶ sort myfile.log | uniq -c | sort -n -r
   4 one
   2 two
   1 three
   1 once

Comments

Your email will never ever be published.

Previous:
Find the largest node_modules directories with bash September 30, 2022 Linux, Bash, macOS
Next:
First impressions trying out Rome to format/lint my TypeScript and JavaScript November 14, 2022 Node, JavaScript
Related by category:
fnm is much faster than nvm. December 28, 2023 macOS
Set up iTerm to delete whole words on Option-Backspace May 13, 2025 macOS
set -ex - The most useful bash trick of the year August 31, 2014 Linux
Be careful with Date.toLocaleDateString() in JavaScript May 8, 2023 macOS
Related by keyword:
set -ex - The most useful bash trick of the year August 31, 2014 Linux
How to sort case insensitively with empty strings last in Django April 3, 2022 Python, Django, PostgreSQL
How to intercept and react to non-zero exits in bash February 23, 2023 Bash, GitHub
Run something forever in bash until you want to stop it February 13, 2018 Linux