awk - continue when encountered division error

Hello,

How can I add a logic to awk to tell it to print 0 when encountering a division by zero attempted? Below is the code. Everything in the code works fine except the piece that I want to calculate read/write IO size. I take the kbr[j] / rs[j] and kbw[j] / ws[j]. There are times when the iostat data does not have any kbr or kbw.

thanks,

awk '
   /^Device:/{++i}
   /^dm-/{rs+=$(NF-8);ws+=$(NF-7);kbr+=$(NF-6);kbw+=$(NF-5)};
   END{
       printf ("%s, %s, %s, %s, %s, %s, %s, %s\n"), "Sample", "r/s", "w/s", "rIOsize", "wIOsize", "KB_read/s", "KB_write/s", "Total KB", "%Read/s", "%Write/s"
       for(j=1;j<=i;j++) if (kbr[j] + kbw[j])
           printf ("%s, %6.2f, %6.2f, %6.2f, %6.2f, %06.2f, %06.2f, %06.2f, %02.2f%, %02.2f%\n"), "Sample "j, rs[j], ws[j],
           kbr[j] / rs[j], kbw[j] / ws[j],
           kbr[j], kbw[j], kbr[j] + kbw[j],
           100 * kbr[j] / (kbr[j] + kbw[j]),
           100 * kbw[j] / (kbr[j] + kbw[j])}' OFS=, $FILE

Use a Conditional Expression:

        rs[j] ? kbr[j] / rs[j] : "0",
        ws[j] ? kbw[j] / ws[j] : "0",
        kbr[j], kbw[j], kbr[j] + kbw[j],
        (kbr[j] + kbw[j]) ? 100 * kbr[j] / (kbr[j] + kbw[j]) : "0",
        (kbr[j] + kbw[j]) ? 100 * kbw[j] / (kbr[j] + kbw[j]) : "0"
1 Like

gee...why not simply test for when the denominator is zero?

(kbr[j] + kbw[j]) 

Thanks Yoda. That works great.

or implementing a div function:

function div(a,b) {
   return (b)?a/b:0
}

Thank you, all. Much appreciated.

TD