- 论坛徽章:
- 0
|
用awk处理一个数据库文件: )
# 初始化模块
BEGIN { FS=":"
print "\t\t\t***CAMPAIGN 1998 CONTRIBUTIONS***"
print "---------------------------------------------------------------------------------"
print "NAME\t\t\tPHONE\t Jan | Feb | Mar | Total Donated"
print "---------------------------------------------------------------------------------"
}
{
gsub(/\$/,""
# gsub将$全部清除掉,使下面能够进行数值运算。
$6=$3+$4+$5
# 格式化输出所有数据
printf("%-20s%-16s%-10.2f%.2f\t%.2f\t %10.2f\n",$1,$2,$3,$4,$5,$6)
}
# 计算所有donation的和。
{total+=$6}
# 下面是排序操作
{
for(i=3;i<NF-1;i++) {
# 将i域赋值到数组dona
dona[i-1]=$i
# dona[0]将永远保存最大值
if(dona[0]<dona[i-1]) dona[0]=dona[i-1]
# 若dona[1]=0则将dona[2]赋值到dona[1]
if(dona[1]==0) dona[1]=dona[2]
# dona[1]将永远保存最小值
if(dona[1]>dona[i-1]) dona[1]=dona[i-1];
}
}
{
# 下面将得到最大贡献者的名字及相应的电话号码
if(max<$6) {
name=$1;
max=$6;
}
# 下面将得到贡献大于500的人的名字及其相应的电话号码
if($6>500) {
j++;
group[j]=$1"--";
telephone[j]=$2;
}
}
# 结束模块
END {
print "---------------------------------------------------------------------------------"
print "\t\t\t\t SUMMARY"
print "---------------------------------------------------------------------------------"
# 输出所有donation的和。
printf("The campaign received a total of $%.2f for this quarter.\n",total)
# 输出平均值
printf("The average donation for the %d contributors was $%.2f.\n",NR,total/NR)
# 输出单月最大贡献额
printf("The highest contribution was $%.2f.\n",dona[0])
# 输出单月最小贡献额
printf("The lowest contribution was $%.2f.\n",dona[1])
# 将name分割到数组nick
split(name,nick," "
# 输出全部贡献额的最大值及其名字
printf("The highest total contribution was $%.2f made by %s\n",max,name)
# 输出该人的first name
printf("\t\t\t\t ***THANKS %s ***\n",nick[1])
# 输出贡献值大于500的所有人的名字及其telephone,要求按last name的字母顺序输出
print "The following people donated over $500 to the campaign!\nThey are eligible for the quarterly drawing !!
\nListed are their names ( sorted by last names ) and phone numbers:"
# 下面将最后一句话输出赋值到group[j+1]
group[j+1]="\tThanks to all of you for your continued support!!"
# 下面是对group数组进行排序输出;这个地方我试过通过赋值到新的域然后再排序输出,但最后的那句"thanks ..."还是不能在最后一行输出
,只能在末尾同样加入 | "sort +1 -2"才得到结果,但实质还是和数组的方法差不多,不知道该如何更好地解决。
for(i=1;i<=j+1;i++) print "\t"grouptelephone | "sort +1 -2"
} |
|