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 CSV file that contains two columns. I want to compare the two columns and print the number of matches.

file1

M,M
A,M
A,A
M,A

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

4 Answers 4

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 at 4:37
    
the columns are seperated by comma. the input file is a csv file –  Rincy Raphael May 26 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 at 4:50
    
no there is no black lines... –  Rincy Raphael May 26 at 4:51
1  
@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 at 5:00
awk -F, '!/^$/ && $1 == $2 { numMatch++ }; END { print numMatch }' YourFile
share|improve this answer

With GNU grep:

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

With your updated input:

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

Updated

With awk:

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

If you can use perl:

$ perl -F',' -anle 'print $F[0] eq $F[1] ? $F[1] : 0' file
M
0
A
0
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

 
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.