Given a list of numbers in a field, how to sum them and print them in an (n)awk script?

153 views Asked by At

Given this list of names and numbers:

Kirilienko:47
James:23 
Bryant:24
Durant:35
Griffin:32

How would I find sum the numbers in the second field and print them in an awk script, in the sentence:

print "The total number of these five players is [161]."

I've done a bit of research and saw the general way to sum a column was with awk {sum += $3} END{print sum}. I've tried to implement this in my script, only to return sum = 0.

2

There are 2 answers

3
heemayl On BEST ANSWER

Set the field separator as :, and get the sum of the second field. In the END block print the sum with desired text:

awk -F: '{sum+=$2} END{print "The total number of these five players is ["sum"]."}' file.txt

Example:

% cat file.txt
Kirilienko:47
James:23 
Bryant:24
Durant:35
Griffin:32

% awk -F: '{sum+=$2} END{print "The total number of these five players is ["sum"]."}' file.txt
The total number of these five players is [161].
0
I0_ol On

While the question specifies awk, it never hurts to have other options. In this particular case you can also do this purely in Bash:

sum=0
while read num
do 
    num="${num#*:}"
    sum=$(( $num + $sum ))
done < file.txt
echo "The total number of these five players is $sum"

Output:

The total number of these five players is 161