日期:2014-05-16  浏览次数:20808 次

UNIX SHELL范例精解awk习题

题目(书中图片):



题目文件:

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 
Nancy McNeil:(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 
(下载地址:)



我的做法:

#Scriptname:xxx
#type:awk script
BEGIN{
FS=":"    #设置分隔符冒号:
total=0;     #所有人捐款总数
print "\n\t\t***CAMPAIGN 2004 CONTRJBUTIONS***"
print "--------------------------------------------------------------------------"
printf " NAME\t\t PHONE\t Jan | Feb | Mar | Total Donated\n"
print "--------------------------------------------------------------------------"
}    #头信息输出
{sum=$3+$4+$5;    #每个人的捐款总数
printf("%-20s%-17s%-8.2f%-8.2f%-8.2f%.2f\n",$1,$2,$3,$4,$5,sum)       #主体输出
total+=sum;   #计算所有人的捐款总数
if(sum>500){
phone[$1]=$2    #把所有捐款捐款总数大于500的保存到数组phone中,用名字作为数组下标索引
}
if(sum>max){
max=sum;    #个人捐款最多的数目
name=$1;    #个人捐款最多的人我名字
}
}
END{
print "--------------------------------------------------------------------------"
print "\t\t\t\t SUMMARY"
print "--------------------------------------------------------------------------"
printf("The campaign received a total of $%.2f for this quarter.\n",total)
printf("The average donation for the 12 contributors was $%.2f.\n",total/12)
printf("The highest total contribution was $%.2f by %s.\n",max,name)
split(name,names," ")   #把名字用空格符分到names数组
printf("\t\t\t***THANKS %s***\n",names[1]) #输出first name
printf("The following people donated over $500 to the campaign.\n")  #下面所有人的捐款都大于500
print "They are eligible for the quarterly drawing!!"
print "Lested are their names(sorted by last names) and phone numbers:"  #用last name排序
for(i in phone){
printf "\t%s--%s\n",i,phone[i]|"sort -k2"  #输出收集到管道,开启排序,然后输出
}
close("sort -k2")   #关闭排序,否则下面语句也参与排序,关闭语句和开启语句要一致
print "\t Thanks to all of you for your continued support!!"
}

源码下载地址: