LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to handle division by zero in awk (https://www.linuxquestions.org/questions/programming-9/how-to-handle-division-by-zero-in-awk-883359/)

dazdaz 05-29-2011 11:22 AM

how to handle division by zero in awk
 
Hi, I have wrote a little awk script below.

Sometimes the variables will be 0 and sometimes not, and of course the output may also be 0%...

What is the best method to handle division by zero errors in awk.

Code:

awk '/SwapFree:/ {swapfree = $2}; /SwapTotal:/ {swaptotal = $2}; /SwapCached:/ {swapcached = $2}; {printf "Linux Swap utilisation : %.2f%\n", swapfree /(swaptotal+swapcached)}' /proc/meminfo
awk: (FILENAME=/proc/meminfo FNR=1) fatal: division by zero attempted


David the H. 05-29-2011 12:36 PM

What do you want the script to do if the value is zero? Figure that out, then simply run a test on the variables before the print statement to implement the correction.

Since your denominator is the sum of two variables, you may want to first pipe the sum into a new variable and test that. If that's zero, then you can reset it to a new value, or tell it to print something else, or whatever.


Edit: I just tried actually running your code, and I believe your problem is not quite what you think it is. The way it's written, the printf command attempts to run on every line of the file, and so it errors out before it reaches the lines you want. Move it into the END block so that it only prints after the whole file has been read and all the variables have been set.
Code:


awk '/SwapFree:/ {swapfree = $2}; /SwapTotal:/ {swaptotal = $2}; /SwapCached:/ {swapcached = $2}; END{printf "Linux Swap utilisation : %.2f%\n", swapfree /(swaptotal+swapcached)}' /proc/meminfo


grail 05-29-2011 07:15 PM

Another alternative would be to simply use your variables as the test to your print:
Code:

awk '/SwapFree:/ {swapfree = $2}/SwapTotal:/ {swaptotal = $2}/SwapCached:/ {swapcached = $2} swapfree && swaptotal && swapcached {printf "Linux Swap utilisation : %.2f%\n", swapfree /(swaptotal+swapcached);exit}' /proc/meminfo
Also notice the exit I placed in as well. This is because once all the variables have been set it will print a result for all remaining lines of the input.


All times are GMT -5. The time now is 12:11 AM.