arraysbashfield

Computing sum of specific field from array entries


I have an array trf. Would like to compute the sum of the second element in each array entry.

Example of array contents

trf=( "2 13 144" "3 21 256" "5 34 389" )

Here is the current implementation, but I do not find it robust enough. For instance, it fails with arbitrary number of elements (but considered constant from one array element to another) in each array entry.

   cnt=0
   m=${#trf[@]}
   while (( cnt < m )); do
     while read -r one two three
     do
       sum+="$two"+
     done <<< $(echo ${array[$count]})
     let count=$count+1
   done

   sum+=0
   result=`echo "$sum" | /usr/bin/bc -l`

Solution

  • You're making it way too complicated. Something like

    #!/usr/bin/env bash
    trf=( "2 13 144" "3 21 256" "5 34 389" )
    declare -i sum=0 # Integer attribute; arithmetic evaluation happens when assigned
    for (( n = 0; n < ${#trf[@]}; n++)); do
        read -r _ val _ <<<"${trf[n]}"
        sum+=$val
    done
    printf "%d\n" "$sum"
    

    in pure bash, or just use awk (This is handy if you have floating point numbers in your real data):

    printf "%s\n" "${trf[@]}" | awk '{ sum += $2 } END { print sum }'