Need help with AWK math

I am trying to do some math, so that I can compare the average of six numbers to a variable.

Here is what it looks like (note that when I divide really big numbers, it isn't a real number):

[@ns1 ~]$ tail -n 6 named.stats | awk -F\, '{print$1}'
1141804
1140566
1139429
1134210
1084682
895045
[@ns1 ~]$ tail -n 6 named.stats | awk -F\, '{print$1}' | awk '{ sum+=$1} END {print sum/6}'
1.08929e+06

But if I calculate smaller numbers:

[@ns1 ~]$ tail -n 6 named.stats | awk -F\, '{print$1}'
2
3452
459
7772
442
10
[@ns1 ~]$ tail -n 6 named.stats | awk -F\, '{print$1}' | awk '{ sum+=$1} END {print sum/6}'
2022.83

Any suggestions? Will it work like that?

Here is how I am comparing:

MAX=`echo 700000`
LASTINV=`tail -n 1 $QLOG | awk -F\, '{print $1}'`
LASTHOUR=`tail -n 6 $QLOG | awk -F\, '{print $1}' | awk '{ sum+=$1} END {print sum/6}'`

CHANGE=`echo "$LASTINV $LASTHOUR" | awk '{if (($1/$2) > 5) {print "EXCEED";} else {print "NOMINAL";}}'`
      if [ "$CHANGE" = "EXCEED" ]
      then

Here is what the variables look like, for example:

[@ns1 ~]$ tail -n 1 named.stats
10,24-Apr-2012,19:50

LASTINV:
[@ns1 ~]$ tail -n 1 named.stats | awk -F\, '{print $1}'
10

[@ns1 ~]$ tail -n 6 named.stats
1141804,24-Apr-2012,19:00
1140566,24-Apr-2012,19:10
1139429,24-Apr-2012,19:20
1134210,24-Apr-2012,19:30
1084682,24-Apr-2012,19:40
895045,24-Apr-2012,19:50

I hope I have given you enough to help me.

I appreciate your help!

Hi, try

END {printf "%d\n",sum/6}

or

END {printf "%.2f\n",sum/6}
1 Like

Perfect!

Thank you so much. Do you mind explaining what you did to me?

printf is a function found in many different programming language for convenient formatting of numbers and strings. Its first argument describes how to format all the arguments afterwards when printing them.

%d means 'print as integer', so it will never show a number with decimal points, sufficiently small numbers will simply become zero.

%f means 'print as floating point'.

%.2f means 'print as floating point to two decimal places'.

There's lots more. See 'man 3 printf' for details on how the arguments generally work.

1 Like