鉴于此名称和数字列表:
Kirilienko:47
James:23
Bryant:24
Durant:35
Griffin:32
如何在第二个字段中找到数字的总和并在awk 脚本中打印出来,在句子中:
print "The total number of these five players is [161]."
我做了一些研究,看到总结列的一般方法是awk {sum += $3} END{print sum}
。我试图在我的脚本中实现这一点,只返回sum = 0。
答案 0 :(得分:1)
将字段分隔符设置为:
,并获取第二个字段的总和。在END
块中打印带有所需文本的总和:
awk -F: '{sum+=$2} END{print "The total number of these five players is ["sum"]."}' file.txt
示例:强>
% 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].
答案 1 :(得分:0)
虽然问题指明了awk
,但是有其他选择永远不会受到伤害。在这种特殊情况下,你也可以在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"
输出:
The total number of these five players is 161