gpt4 book ai didi

linux - 如何在一行或多行中查找具有相同值的行并使用 awk 添加值

转载 作者:太空狗 更新时间:2023-10-29 11:49:22 25 4
gpt4 key购买 nike

我有以下数据:

    Name,Team,First Test, Second Test, Third Test
Tom,Red,5,17,22
Joe,Green,3,14,22
Maria,Blue,6,18,21
Fred,Blue,2,15,23
Carlos,Red,-1,15,24
Phuong,Green,7,19,21
Enrique,Green,3,16,20
Nancy,Red,9,12,24

我需要找到绿队平均值。我在如何完成它方面遇到了一些麻烦。

到目前为止我有:

awk '/Green/' teamlist.txt

这给了我以下结果:

Joe,Green,3,14,22
Phuong,Green,7,19,21
Enrique,Green,3,16,20

但是,当我尝试打印以下语句时:

awk '/Green/ {print $3, $4, $5}' teamlist.txt

我只是收到一个空白输出,没有任何显示。我还需要添加列 $3、$4 和 $5,然后除以 9。

到目前为止,这是我的代码:

#Begin. Start with the Field Separator using comma.
BEGIN {
FS=",";
}

#Middle.
{
if (NR > 1)

{
name[NR] = $1; #Name record is field 1
average[NR] = ($3 + $4 + $5) / 3; #Average is number of records which are fields 3,4,5. Add them up and then divide by 3.

testOneAverage += $3 #Average of test one. Keeps adding field three to itself for the number of records.

testTwoAverage += $4 #Average of test two. Keeps adding field four to itself for the number of records.
testThreeAverage += $5 #Average of test three. Keeps adding field five to itself for the number of records.

}


}

#End
END {
print "Name Average";
print "------ ------";

i = 1;

while (i <= FNR) {
printf("%-10s %7.2f\n", name[i] , average[i++]);
}

if (NR > 0) {
print "---------------------------";
print "Average for Test 1: " testOneAverage / 8;
print "Average for Test 2: " testTwoAverage /8;
print "Average for Test 3: " testThreeAverage /8;
}

最佳答案

你的短语:我需要找到绿队平均 + 添加 $3、$4 和 $5 列,然后除以 9 - 表示您想要获得总体/总平均值。

Awk解决方案:

awk -F',' 'NR>1 && $2=="Green"{ ++c; sum+=$3+$4+$5 }END{ print sum/(c*3) }'  file

输出:

13.8889

关于linux - 如何在一行或多行中查找具有相同值的行并使用 awk 添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46820904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com