Compare 2 columns from the same file and print a value depending on the result

Hello Unix gurus,

I have a file with this format (example values):

label1	1	0
label2	1	0
label3	0.4	0.6
label4	0.5	0.5
label5	0.1	0.9
label6	0.9	0.1

in which:
column 1 is a row label
column 2 and 3 are values

I would like to do a simple operation on this table and get the following output file:

label1	0
label2	0
label3	2
label4	1
label5	2
label6	0

in which the value in column 2 is:
"0" if input column 2 > input column 3
"1" if input column 2 = input column 3
"2" if input column 2 < input column 3

I think is possible in bash/awk but I am not sure (other possibilities welcome)

Many thanks for your help and time.

KS

Any attempts / ideas / thoughts from your side? Even partial attempts welcome.

Thanks for your quick reply!
Of course. So far I have:

awk '{
if ($3 > $2)
	print $1,"2";
else
	print $1,"0";
}' file1 > file2

but I am not sure how to deal with the case in which $3 and $2 would be the exact same value.

thanks

Mayhap another if ... then ... construct?

1 Like

Sorry for the simplicity, I'm just starting! :wink:
I didn't know how to combine them with "else if".

awk '{
if ($3 > $2)
	print $1,"2";
else if($3 < $2)
	print $1,"0";
else if ($3 = $2)
	print $1,"1";
}' file1

So you've done it on your own! Congrats!

Next time you might consider

awk '{print $1, ($2>$3)?0:($2<$3)?1:2}' file3
label1 0
label2 0
label3 1
label4 2
label5 1
label6 0

as well.

1 Like

Thank you for the kind word! It's a very slow process :wink:

Do you just list the conditions as x:y:z with the last one being a bit like "else"?
Thanks again

The "if?then:else" is a "value if", a ternary operator.
Here with another ternary operator in the "else".

In your explicit if-then-else clause it must be
else if ($3 == $2) because $3 = $2 is an assignment not a comparison.
Or just else without a condition, because what is neither less nor greater must be equal.

1 Like

Thank you very much for the clarification!