# Count rows with specific integer in a column

I have 6 columns, each with multiple rows.

I want to count the number of rows which have the integer 4 or 5 in the fifth column.

``````A1 jhfj jdhfjkhd kdkfjjh 5 jhsdjkfh
A2 ujhf jhdfhsd  dsfkks  4 jhsdfjhs
A3 jhfj jdhfjkhd kdkfjjh 5 jhsdjkfh
A4 jhfj jdhfjkhd kdkfjjh 5 jhsdjkfh
A5 ujhf jhdfhsd  dsfkks  4 jhsdfjhs
``````

In the example presented, the result should be three for lines with a 5, and two for lines with a 4.

• You mean that you want rows that do not contain 4 or 5 in the 5th column? Feb 13 '14 at 8:25
• Skipping lines with 4 or 5 in the 5th column, what do you want to count? Number of lines, sum of the line lengths, sum of the 5 the column values, total number of columns? Feb 13 '14 at 8:37
• @Zelda I assume the OP meant "No.", not "no". Feb 13 '14 at 8:45
• @ChrisDown That could be, on reread I still can't figure out what is that "which has" refers to. I would assume someone using nr. in that case anyway. Feb 13 '14 at 8:55
• @Zelda Standard British notation is "No." -- the OP's name (from the username) is "Taraka Ramji", a typically Indian name, and India tends towards using British abbreviation conventions. I'm just guessing here :-) Feb 13 '14 at 8:59

This will give you the gross counts for rows with a 4 and rows with a 5 in the 5th column.

``````\$ awk '{print \$5}' somefile | sort | uniq -c
2 4
3 5
``````

The counts the first digit in the output, the 2nd column is which number it corresponds to from the 5th column.

• Note to the OP: this assumes all rows have either a 4 or a 5 in the fifth column; otherwise, it will print counts for other values in the fifth column as well. Feb 16 '14 at 10:10

Using only `awk`:

``````awk '
\$5==4{c4++};
\$5==5{c5++};
END{
print "Fours: "c4;
print "Fives: "c5;
}' your_file
``````

or `perl`:

``````perl -lane '
\$count{\$F[4]}++;
END{
print "Fours: \$count{4}";
print "Fives: \$count{5}"
}' your_file
``````

Following execution will lead you to your required output.

1) awk '{print \$5}' 4.txt | grep -c 4

2) awk '{print \$5}' 4.txt | grep -c 5

3) awk '{print \$5}' 4.txt | sort | uniq -c

Explanation:

-c option will count the no. of pattern matched in all above cases

``````cat file | awk '{print \$1,\$2,\$3,\$4,\$6}'
``````

output is:

``````A1 jhfj jdhfjkhd kdkfjjh jhsdjkfh
A2 ujhf jhdfhsd dsfkks jhsdfjhs
A3 jhfj jdhfjkhd kdkfjjh jhsdjkfh
A4 jhfj jdhfjkhd kdkfjjh jhsdjkfh
A5 ujhf jhdfhsd dsfkks jhsdfjhs
``````

there is no 5 and 4 in the lines in th 5th column. From your post I hope that you requested like this.

• So what it is that is being counted (as requested by the OP)? Feb 13 '14 at 8:57
• `awk` takes the filename as an argument: no need for UUOC... Feb 13 '14 at 9:27