awk Division By Zero Bypass

Hi Friends,

I don't understand why "a" is always being printed as zero, when I execute the following command.

awk '{if($6||$8||$10||$12==0)a=b=c=d=0;else (a=$5/$6);(b=$7/$8);(c=$9/$10);(d=$11/$12); {print $1"\t"$2"\t"$3"\t"$4"\t"$5"\t"$6"\t"a"\t"$7"\t"$8"\t"b"\t"$9"\t"$10"\t"c"\t"$11"\t"$12"\t"d"\t"$13,$14}}' input

Hello,

Please let know the Output you are expecting, including the input.

Thanks,
R. Singh

Dear R.Singh,

The input is a 100 column long data.

I am trying to divide column 5 with 6, 7 with 8, 9 with 10 and 11 with 12.

If columns 6,8,10 or 12 has zero, awk is complaining that fatal division by zero was attempted.

So, I thought I will read the 6,8,10 and 12th columns first, and if there is a zero, I would make the division output to be zero.

But, except for the division of column 5 with 6, all others are giving correct output. I don't know why this particular division is printing only zeroes even when column 6 is not zero.

Try this instead:

awk '
        {
                a = ( $6 == 0 ) ? 0 : $5 / $6
                b = ( $8 == 0 ) ? 0 : $7 / $8
                c = ( $10 == 0 ) ? 0 : $9 / $10
                d = ( $12 == 0 ) ? 0 : $11 / $12
                print $1, $2, $3, $4, $5, $6, a, $7, $8, b, $9, $10, c, $11, $12, d, $13, $14
        }
' OFS= '\t' input
1 Like

Thanks Yoda. It worked.

or:

awk '
    function div (a,b){
      return (b)?a/b:0
    }
    {                 
       print $1, $2, $3, $4, $5, $6, div($5,$6), $7, $8, div($7,$8), $9, $10, div($9,$10), $11, $12, div($11,$12), $13, $14  
    }
' OFS= '\t' input
2 Likes

Your

awk '{if($6||$8||$10||$12==0)a=b=c=d=0...

will set a,b,c,d to zero if EITHER $6<>0 or $8<>0 or $10<>0 or $12==0, so I guess this is opposite to what you wanted to do...