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 file that I need to compare the values in two columns with another two columns. For examples:

Item  A     B     C    D
1    201  3101   3101 201
2   3101   201    202 3101  
3   3101   201    201 3102 
4   3101   201   3202 202 

So what I trying to do is comparing column A & B to C & D, but values in column A & B and C & D are interchangeable. And I would like to have a output like 2 if both values are the same, 1 if only one is match and 0 if both are not match. The answer would be something like this

Item  A     B     C      D   Output
1    201  3101   3101   201    2
2   3101   201    202  3101    1
3   3101   201    201  3102    1
4   3101   201   3202   202    0

How would I be able to achieve this?

share|improve this question

2 Answers 2

This awk onliner gets you very close to the desired output (at least the numbers are correct).

awk '{n=0} $2==$4 {n=n+1} $2==$5 {n=n+1} $3==$4 {n=n+1} $3==$5 {n=n+1} {print $0, n}' inputfile

Basic awk is used here. The string between quotes is executed for each line, while the block between brackets is only executed when the statement in front of it is true. $i refers to the i-th column.

share|improve this answer
2  
if A,B,C,D are identical, output will be 4. i think it's better to merge $2==$4 {n=n+1} $2==$5 {n=n+1} to $2==$4 || $2==$5 {n++}, and merge $3==$4 {n=n+1} $3==$5 {n=n+1} to $3==$4 || $3==$5 {n++} –  LiuYan 刘研 Feb 18 '13 at 8:35
    
@LiuYan刘研 True, that would be an alternative. It depends on the desired behavior. –  Bernhard Feb 18 '13 at 8:57

Another awk answer, the core part is same. This is a awk script, and more readable

#!/bin/awk -f

BEGIN{ print "Item  A   B   C   D   Output"}
{
    count=0;
    if($2==$4) count+=1;
    if($2==$5) count+=1;
    if($3==$4) count+=1;
    if($3==$5) count+=1;
    if(NR != 1)
        print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $5 "\t" count
}
END{} #Done

Useful Link to awk scripting

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.