需要有人帮忙计算每个地区的总人口并打印地区名称、人口和平均人口。
States.txt(文件):
State Population SqMi Region
------------------------------------------
California 39.37 163.7 West
Texas 29.36 268.6 South
Florida 21.73 65.7 South
New_York 19.33 54.7 NorthEast
Pennsylvania 12.78 46.1 NorthEast
Illinois 12.59 57.9 Midwest
Ohio 11.69 44.8 Midwest
Georgia 10.71 59.4 South
North_Carolina 10.60 53.8 South
Michigan 9.97 96.7 Midwest
**输出应类似于“”
Region Total Average
---------------------------
South 72.40 18.10
Midwest 34.25 11.42
NorthEast 32.11 16.05
West 39.37 39.37
答案1
和awk
:
awk '
FNR>2{ total[$4]+=$2; count[$4]+=1 }
END{
print "Region Total Average"
print "---------------------------"
for (i in total){ printf "%s %.2f %.2f" ORS, i, total[i], total[i]/count[i] }
}
' States.txt