# How to count many lines have the same number in two columns?

I need to compare the numbers in two columns and count how many lines have the same value in both columns. For example:

``````17 19
17 17
17 18
19 19
25 22
34 34
``````

Expected output:

``````3
``````

I can't sort them because each line is a specific gene and I can't use `awk` because technically we haven't seen it in class yet. Is there any way to do this with `grep`?

• Do you expect someone else to do your homework? – RalfFriedl Apr 4 at 6:36
• Could you say something about that thing you mentioned about sorting? Sorting the input would probably not help in solving this, but I'm confused as to why you mention it at all, mostly because it implies that you might have something other than positive integers as data. This makes me wonder what the data actually is and whether it contains whitespace characters other than between the columns. – Kusalananda Apr 4 at 11:58
• There are only positive integrers between the two columns, I only mentioned sorting because initially I thought of using it in something in combination with uniq and then get only those that matched, but couldn't do it. You're right, it probably does not help to solve it. – Erandi Apr 5 at 23:48

One way would be to use `grep` with its Extended Regular Expressions mode ( `-E`, to use back-references), to match the value in column 1 and print all those lines whose second column value is also the same.

The first part `([^ ]+)` captures the value in first column, and `\1` refers to the captured value, so together they represent to match those lines whose value captured in the first column is also the same as second. The `-c` is for printing count of those lines returned.

``````grep -cE '([^ ]+) \1' file
``````

Also, to avoid partial matches add another flag `-x` and ensure there are no characters (even white-spaces) before and after the line.

• Note that POSIX EREs (contrary to BREs) don't have back references. POSIXly, you'd need `grep -cx '[[:space:]]*\([^[:space:]]\{1,\}\)[[:space:]]\{1,\}\1[[:space:]]*'` as the equivalent of GNU `grep`'s `grep -Exc '\s*(\S+)\s+\1\s*'` – Stéphane Chazelas Apr 4 at 11:06

Using awk :

``````awk '\$1==\$2{count++} END {print count}' kk
3
``````
• `\$1==\$2` match field 1 and 2
• `count++` if match found increment the counter.
• `print count` print the final counter value/
• OP says they can’t use awk – Inian Apr 4 at 5:44
• hooo ok... will update.. – msp9011 Apr 4 at 5:48
• @Inian `awk` may not be what the user is supposed to use, but it is the right tool for the job. There is no point learning to use the wrong tools. It is additionally a standard tool that is available on any Unix system. – Kusalananda Apr 4 at 12:15
• @Kusalananda: Agreed, I would have preferred `awk` if not for the OP's disclaimer – Inian Apr 4 at 12:17