Linux command or script counting duplicated lines in a text file?

timeon picture timeon · Jun 23, 2011 · Viewed 90.2k times · Source

If I have a text file with the following conent

red apple
green apple
green apple
orange
orange
orange

Is there a Linux command or script that I can use to get the following result?

1 red apple
2 green apple
3 orange

Answer

borrible picture borrible · Jun 23, 2011

Send it through sort (to put adjacent items together) then uniq -c to give counts, i.e.:

sort filename | uniq -c

and to get that list in sorted order (by frequency) you can

sort filename | uniq -c | sort -nr