Reputation: 33
I seek your help in storing awk returning values in an array for my awk for loop using if else conditions.
If $3 == $7
then print $9 multiplied by $4
else print $4 multiplied by (2 minus $9)
I got this working so far by:
awk '{if ($3 == $7) print $9*$4; else print $4*(2-$9);}' file >outfile
the above code works for the first data column ($9
). However, I want to loop through all columns from 9 to 1547 and return an array containing the returning values. This should be simple enough but I cant seem to understand some basic concepts here.
So far I understand the need to declare the number of loops, before the actual function, by:
awk ' {for(i=9;i<=NF;i++)} END {if ($3 == $7) print $i*$4; else print $4*(2-$i);}'
However, how and when to declare the array is beyond me (biologist). Any help would be highly appreciated.
Example:
input (big file.. here column 1-10):
rs2070501 22 A 0.0206 0.337855 rs2070501 G A 0.977 0.066
output:
0.0210738
here the else statement kicks in ($3 * (2-$9)
How to get awk to print out the array 9-Nth, and not just column 9
Upvotes: 3
Views: 44908
Reputation: 189417
Try with this.
awk '{
for(i=9; i<=NF; ++i)
printf "%s%f",
(i==9 ? "" : " "),
($3 == $7 ? $i*$4 : $4*(2-$i));
printf "\n"
}' filename
The ( test ? when : else )
is just a shorthand; the stuff after ?
gets evaluated if the test is true, and the stuff after :
otherwise. So it prints an empty separator for the first field, and a space otherwise; and chooses how to calculate the value of the field depending on whether $3 == $7
is true.
Upvotes: 5