编写一个名为labscript3.awk的脚本,打印2014年发货的所有订单。打印区域、项目类型和总利润。最后,它应该打印出平均总利润(仅针对这些订单)。(5分)
我尝试了下面的代码,但它没有工作。只有打印的"=======“
#!/usr/bin/awk -f
BEGIN {
printf "%-25s %-16s %-10s\n","region","item type","total profit"
print "============================================================="
cnt=0
sum=0
}
{
if($1==2014){
printf "%-25s %-16s %.2f\n",$2,$3,$4
++cnt
sum += $4
}
{
END{
print "============================================================="
printf "The average total profit is : %.2f\n", sum/cnt
}我做错什么了?
发布于 2022-08-24 19:19:16
% ./aw.awk < in
region item type total profit
=============================================================
0 0 12.00
1 1 13.00
2 2 14.00
=============================================================
The average total profit is : 13.00我修正了你的代码错误,得到了结果。
#!/usr/bin/awk -f
BEGIN {
printf "%-25s %-16s %-10s\n","region","item type","total profit"
print "============================================================="
cnt=0
sum=0
}
{
if($1==2014){
printf "%-25s %-16s %.2f\n",$2,$3,$4
++cnt
sum += $4
}
}
END{
print "============================================================="
printf "The average total profit is : %.2f\n", sum/cnt
}将这些数据保存在“in”文件中:
2014 0 0 12
2014 1 1 13
2014 2 2 14发布于 2022-08-24 19:20:32
你可能会调用你的代码
awk -f my_program.awk其中awk将执行BEGIN块,并且由于没有提供文件名,awk等待在stdin上接收数据。
提供数据文件名,如James在回答中所演示的那样。
https://stackoverflow.com/questions/73478500
复制相似问题