Search code examples
awkgawk

AWK - if and printf, before or within


I have the following printf

printf ("%-6s\t%6.3f\n",msg,sum[msg]/count[msg])

the arrays to this are as follows:

sum[$2] += $3
count[$2]++

$2 = test1 $3 = 0 - 9 on different lines at random

I am to do a if statement to say if either sum[msg] or count[msg] == 0 then replace with -

I am not sure if I have to do the following:

if (count[msg] == 0 || sum[msg] == 0) {
printf ("%-6s\t-\n",msg)
}

or is it possible to put the if within the printf like the following:

printf ("%-6s\t%6.3f\n",msg,if (count[msg] == 0 || sum[msg] == 0) {print -} else sum[msg]/count[msg])

Also if the actual sum[$2] += $3 has no matching rows will that return 0 or null

all help is greatly appreciated.


Solution

  • printf "%-6s\t%s\n",msg,(sum[msg]*count[msg]?sprintf("%6.3f",sum[msg]/count[msg]):"-")
    

    but please do read the book Effective Awk Programming, 4th Edition, by Arnold Robbins to get a foundation so you don't have to keep asking for help every step of the way.