单个AWK一次扫描完成统计任务

环境
RedHat Linux 9 + VWWare 8.0 + SSH 3.2.9

任务

下面的文本中包含名字、电话和为党派运动捐款的数额。

名字:电话:1月捐款情况:2月捐款情况:3月捐款情况

Mike Harrington :(510) 548-1278:250:100:175

Christian Dobbins:(408) 538-2358:155:90:201

Susan Dalsass:(206) 654-6279:250:60:50

Archie McNichol:(206) 548-1348:250:100:175

Jody Savage: (206) 548-1278:15:188:150

Guy Quigley:(916) 343-6410:250: 100:175

Dan Savage:(406) 298-7744:450:300:275

NancyMcNeil:(206) 548-1278:250:80:75

John Goldenrod:(916) 348-4278:250:100:175

Chet Main:(510) 548-5258:50:95:135

Tom Savage:(408) 926-3456:250:168:200

Elizabeth Stachelin:(916)440-1763:175:75:300

使用你能用到的任何linux命令脚本产生一个如下的报告,注意,报告中的summery包含对于捐款情况的一些统计信息。

解决

awk -F ":" 'BEGIN{ 
print "            ***FIRST QUARTERLY REPORT **** \n"; 
print "            ***CAMPAIGN 2000 CONTRIBUTIONS ***\n"; 
print "-------------------------------------------------------------------\n"; 
print "  NAME                  PHONE      JAN| Feb| Mar|  Total Danated \n"; 
print "-------------------------------------------------------------------\n"; 

BEGIN{sum=0;total=0;average=0;i=0;highest=0;name;biaozhun=500;firstNames[12];count=0;lastNames[12];person[12]} 
{for(i=0;i<NR;i++){person[i]=$1}} 
{total=$3+$4+$5;sum+=total;average=sum/12;} 
{if(total>highest) highest=total;if(highest == total)name=$1;} 
{if(total>biaozhun){firstNames[count]=$1;lastNames[count]=$2;count++;}} 
{printf("%-20s%12s%5d%5d%5d\t%5d\n",$1,$2,$3,$4,$5,total);} 
END{ 
    print "-------------------------------------------------------------------\n"; 
    print "                      SUMMARY                                    \n"; 
    print "-------------------------------------------------------------------\n"; 
    printf("The campaign received a total of $%d for this quartor\n",sum); 
    printf("The average donation for the %d contributors was $%.2f.\n",NR,average); 
    printf("The highest total contribution was $%.2f made by %s\n",highest,name); 
    printf("                  ***THANKS Dan***                              \n"); 
    printf("The following people donated over \$500 to the campaign          \n"); 
    printf("They are eligible for the quarterly drawing!!                    \n"); 
    printf("Listed are their names (sorted by last names) and phone numbers:  \n"); 
    {OFS="--";$1="\t"$1;} 
    for(i=0;i<count;i++) {print firstNames[i],lastNames[i] | "sort -k 2"}; 
    printf("      Thanks to all of you for your continued support!!      \n"); 
    } 
' salary.txt 

运行效果截图

单个AWK一次扫描完成统计任务

单个AWK一次扫描完成统计任务

参考资料

AWK使用练习

问题提出

这句话(Thanks to all of you for your continued support!! )打印在for之前,for里面有变量就会出现这种情况,for里面只打印纯文本的话就不会出现这个情况。求解释。

linux

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/20500.html