Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a CSV file that contains two columns. I want to compare the two columns and print the number of matches.



Expected output:

If the first columns in the first row is the same, I want to print the second column in the output file, i.e.

M (for first line)
0 (for second line not same, zero value)
A (for third line)
0 (for fourth line not same, zero value)
share|improve this question
awk -F , '{ if ($1 == $2) print $2; else print 0; }' inputfile
share|improve this answer
this code is not working properly. – Rincy Raphael May 26 '14 at 4:37
the columns are seperated by comma. the input file is a csv file – Rincy Raphael May 26 '14 at 4:48
@RincyRaphael I see your new question edit. If you don't ask the right question you won't get the right answer. I will ask again - are there blank lines in your input like you have in your question? – jw013 May 26 '14 at 4:50
no there is no black lines... – Rincy Raphael May 26 '14 at 4:51
@RincyRaphael I am only answering what you have in your question. If you want something put it in your question. Your question says "Expected output: 2" so that is what I gave you. If you want something else ask for it. I can not read your mind. – jw013 May 26 '14 at 5:00
awk -F, '!/^$/ && $1 == $2 { numMatch++ }; END { print numMatch }' YourFile
share|improve this answer

With GNU grep:

$ grep -cP '(.+) \1' file

With your updated input:

$ grep -cP '(.+),\1' file    


With awk:

$ awk -F',' '{print $1 == $2 ? $2 : 0}' file

If you can use perl:

$ perl -F',' -anle 'print $F[0] eq $F[1] ? $F[1] : 0' file
share|improve this answer

Try this awk command,

awk -F, '!/^$/ {if($1==$2) {print $2} else {print "0"}}' file
share|improve this answer

Your Answer


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.