ksennin
September 6, 2017, 2:40pm
1
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
RudiC
September 6, 2017, 2:47pm
2
Any attempts / ideas / thoughts from your side? Even partial attempts welcome.
ksennin
September 6, 2017, 3:01pm
3
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
RudiC
September 6, 2017, 3:09pm
4
Mayhap another if ... then ...
construct?
1 Like
ksennin
September 6, 2017, 3:18pm
5
Sorry for the simplicity, I'm just starting!
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
RudiC
September 6, 2017, 3:39pm
6
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
ksennin
September 6, 2017, 4:27pm
7
Thank you for the kind word! It's a very slow process
rudic:
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.
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
ksennin
September 6, 2017, 8:12pm
9
Thank you very much for the clarification!