LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   awk else if statement (http://www.linuxquestions.org/questions/programming-9/awk-else-if-statement-945815/)

dazdaz 05-18-2012 08:38 PM

awk else if statement
 
I am trying to avoid divide by zero errors and have modified the folowing so that it will account for that, and not print an error.

However something is not correct with the 1-liner's awk syntax. I've tried many variations..

Code:

free -mt | awk '/Swap/ {(if $2 == 0) {print "swap used in % : 0"} else if ($2 != 0) {printf "swap used in % : %.2f\n", $3 / ($2 / 100)}'

Nominal Animal 05-18-2012 09:40 PM

The first ( is on the wrong side of the if statement.

You do a superfluous comparison in the first else case: you already know $2 cannot be zero, so why would you test it again?

(While you use the print and printf statements correctly, there is a high risk of confusion or error. The former prints all its arguments (similar to echo in shell scripts), the latter takes a pattern and optional arguments referred to in the pattern. I prefer to put the parameters to printf in parentheses to emphasize the distinction. Besides, it looks more like the C function then, which is useful, because it works pretty much exactly like the C version.)

You are missing a } at the end.

Try this approach instead:

If the second field is greater than zero, calculate the percentage (by multiplying the third field by a hundred, then dividing by the second field). Then, print out p as a percentage. If $2 was zero, then p is unset, and evaluates to zero.
Code:

free -mt | awk '/Swap/ { if ($2 > 0) p = 100.0 * $3 / $2 ; printf("Swap used: %.2f%%\n", p) }'

dazdaz 05-19-2012 05:56 AM

Thank you, nice methodology.


All times are GMT -5. The time now is 01:26 AM.