3

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

7
  • What do you mean by "return an array"? Can you show sample input and output? Commented May 30, 2012 at 12:55
  • The END block is what happens when all rows have been read. Do you mean something like awk '{ for(i=9; i<=NF; ++i) printf "%s%i", (i==9 ? "" : " "), ($3 == $7 ? $i*$4 : $4*(2-$i)); printf "\n" }' perhaps? Commented May 30, 2012 at 13:00
  • @triplee your code seems promising, but returns only "0" in every cell. But has the right number of columns. Commented May 30, 2012 at 13:08
  • The %i formatting code is for integers; change it to %f for floats. Commented May 30, 2012 at 13:10
  • @general exception indeed.. All lines are processed, but not all columns. Commented May 30, 2012 at 13:12

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.