6

I have a data file, like

7
2
10
9
10
3
2
4
2
4
6

Each line has a single value. I want to count the occurence of each value. For instance, 10 occurs two times in this file.

Is there a simple way to do that under linux without writing formal counting program?

10

Yes, there is:

$ sort -n file | uniq -c

Where -n enables numeric sorting and -c enables counting.

For the above sequence:

$ echo -e '7\n2\n10\n9\n10\n3\n2\n4\n2\n4\n6' | sort -n | uniq -c 
  3 2
  1 3
  2 4
  1 6
  1 7
  1 9
  2 10

(The first columns contains the counts, the 2nd the numbers.)

  • +1 a more readable way to write that echo statement is printf "%s\n" 7 2 10 9 10 3 2 4 2 4 6 – glenn jackman Mar 9 '12 at 20:02
  • Thanks, I did not know uniq has a -c switch – Gowtham Mar 10 '12 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.