1

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.

Anonymous
  • 411
  • 1
  • 4
  • 14

2 Answers2

1

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].
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

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
I0_ol
  • 1,054
  • 1
  • 14
  • 28