LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk not summing correctly? (https://www.linuxquestions.org/questions/linux-newbie-8/awk-not-summing-correctly-4175461473/)

Kustom42 05-10-2013 04:24 PM

awk not summing correctly?
 
Hi All,



Not sure if I'm just missing something here but this looks correct, I've re-written the code a bit to eliminate variables and isolate the awk statement:

Code:

echo "${Mrl101Array[*]}" | tr ' ' "\n" | sort -n -t"_"
Produces the following output:

Code:

16_100_sat
19_100_thur
19_100_wed
26_100_fri
28_100_tue
29_100_sun
30_100_mon

Now the following awk code:

Code:

echo "${Mrl100Array[*]}" | tr ' ' "\n" | sort -n -t"_" | awk 'BEGIN { FS = "_" } ; {sum+=$1} END { print "Average = ",sum}'
Tells me that the sum is 1. I had it as sum/NR to get the average but removed it to see what the sum was because it wasn't working.

Am I just overlooking a small syntax issue here?

Kustom42 05-10-2013 04:28 PM

OK, so I was able to get it to do its math by taking the first code example and redirecting it to a tmp file then awking from that tmp file. Can anyone explain this behavior? I'm not an awk expert so not sure if it has something to do with the array expansion or what.

grail 05-10-2013 11:44 PM

Seems to work just fine for me as is. I would mention that the sort is kind of pointless as is the tr when awk could do it all:
Code:

arr=( 30_100_mon 28_100_tue 19_100_wed 19_100_thur 26_100_fri 16_100_sat 29_100_sun )

echo "${arr[*]}" | awk 'BEGIN { FS = "_"; RS = " " } {sum+=$1} END { print "Average = ",sum}'



All times are GMT -5. The time now is 06:47 AM.