Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 10 down vote accepted

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.)

share|improve this answer
    
+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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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