timeon timeon - 1 year ago 97
Linux Question

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

If I have a text file with the following conent

red apple
green apple
green apple

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download