0

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)
0

4 Answers 4

3
awk -F , '{ if ($1 == $2) print $2; else print 0; }' inputfile
6
  • this code is not working properly. May 26, 2014 at 4:37
  • the columns are seperated by comma. the input file is a csv file May 26, 2014 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, 2014 at 4:50
  • no there is no black lines... May 26, 2014 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, 2014 at 5:00
1
awk -F, '!/^$/ && $1 == $2 { numMatch++ }; END { print numMatch }' YourFile
1

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
1

Try this awk command,

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .