Counting the number of lines having a number greater than 100

awkgrepsed

I have a file with many numbers in it (only numbers and each number is in one line). I want to find out the number of lines in which the number is greater than 100 (or infact anything else). How can I do that?

Best Answer

Let's consider this test file:

$ cat myfile
98
99
100
101
102
103
104
105

Now, let's count the number of lines with a number greater than 100:

$ awk '$1>100{c++} END{print c+0}' myfile
5

How it works

  • $1>100{c++}

    Every time that the number on the line is greater than 100, the variable c is incremented by 1.

  • END{print c+0}

    After we have finished reading the file, the variable c is printed.

    By adding 0 to c, we force awk to treat c like a number. If there were any lines with numbers >100, then c is already a number. If there were not, then c would be an empty (hat tip: iruvar). By adding zero to it, we change the empty string to a 0, giving a more correct output.

Related Question