[awk] Average the second column by the value in the first

Created on November 30, 2026

Use associative arrays in awk to group rows by their first field. Save this input as scores.txt.

apple 10
banana 9
apple 15
banana 12
apple 20

Keep the total and count for each group. After reading every row, divide each total by its count.

awk '
    { total[$1] += $2; count[$1]++ }
    END {
        for (group in count) {
            printf "%s %.2f\n", group, total[group] / count[group]
        }
    }
' scores.txt | sort
apple 15.00
banana 10.50

For example, the banana rows total 21 across two entries, so their average is 10.50. Awk does not specify the order of array keys. Piping the output to sort orders the results by group name.

For a single average across the input, see Calculate an average.

awk Shell command