我正在获取以下数据并尝试使用 awk 输出平均值。
chores.csv
Chore Name,Assigned to,estimate,done?
Laundry,Chelsey,45,N
Wash Windows,Sam,60,Y
Mop kitchen,Sam,20,N
Clean cookware,Chelsey,30,N
Unload dishwasher,Chelsey,10,N
Dust living room,Chelsey,20,N
Wash the dog,Sam,40,N
这是我写的脚本:
#!/bin/awk
BEGIN {
NR>1
FS=","
} $3 > 0 {
i++ ; tot+=$3
avg=tot/i
}
END{
printf "\nAverage: %.2f\n ", avg
}
当我运行它时,我得到不正确的输出
awk -f avg.awk chores.csv
Average: 28.12
答案应该是32.14
您筛选标题行的尝试显然不起作用。一个明显的可能性是这个一般顺序上的东西(未经测试,但足够简单,我希望它无论如何都能工作):
$3 ~ /^[0-9]+$/ {
i++;
tot+=$3;
avg=tot/i;
}
您正在计算标题行,即使它没有您想要的数字。
更改为:
#!/bin/awk
BEGIN {
NR>1
FS=","
} NR>1 && $3 > 0 { # NR>1 check added here
i++;
tot += $3
}
END {
avg=tot/i
printf "\nAverage: %.2f\n ", avg
}