Ratnesh
Ratnesh

Reputation: 1700

Mathematical computation in associative array in awk

I am following this link https://stackoverflow.com/a/54599800/10220825 . I want to create an array to store the value of each key and do some mathematical computation like average, maximum, etc. Here my code:

BEGIN { FS="[: ]+"}
/:/{vals[$1]=vals[$1] OFS $2+0}
END {
         for (key in vals)
         {
                c=0
                sum=0 
                print key vals[key]
                arr[c++]=vals[key]

                for(i=0;i<c;i++)
                {
                        #print arr[0]
                        sum+=sum+arr[i]
                }
                print "Sum = " sum
         }
}

But arr is not able to store the individual value of vals[key] as it seems vals[key] value is stored as string. Please help me to explore more in an associative array in awk, so that I could store the individual value of vals[key] in array. For example: for vals[RAM] I could able to create a temporary array to store individual like: arr[0]=142;arr[1]=149;arr[2]=131. The main purpose for creating a temporary array is to compute mathematical computation like max, min, avg, searching, sorting, etc.

Expected Output:

RAM 142 149 131
Sum= 422
Cache 456 152 184
Sum= 792

My code output:

RAM 142 149 131
Sum= 142
Cache 456 152 184
Sum= 456

Upvotes: 0

Views: 70

Answers (1)

tripleee
tripleee

Reputation: 189679

Calculating the sum for each key immediately when you store it seems like a better approach.

BEGIN { FS="[: ]+" }
/:/ { vals[$1] = vals[$1] OFS $2+0; sum[$1] +=$ 2+0 }
END { for (key in vals) {
    print key vals[key]
    print "Sum= " sum[key] } }

Upvotes: 1

Related Questions