awk中数组是关联数组,它的独特之处是其下标可以是一个字符或一个数值这就可以实现一个词语的缩写和其全称的关联
如array[NBA] = National Basketball Association
可以实现++class_grade[grade] (grade是“A”“B”“C”“D”),这样就可以实现对ABCD出现数量的一个统计,并且用一个语句就可以实现这种结果。
下面是实现对一个班的成绩的统计结果。
$cat grade_student.awk
# letter grade as well as class average.
# $1 = student name ; $2 - $NF = test scres.
# set output filed separator to tab.
BEGIN { OFS = "\t"}
# action applied to all input lines
{
# add uo grades
total = 0
for (i = 2; i <= NF ; ++i)
total += $i
# calculate average
avg = total / (NF -1)
#assign student's average to element of array
student_avg[NR] = avg
#determine letter grade
if (avg >= 90) grade = "A"
else if (avg >= 80) grade = "B"
else if (avg >= 70) grade = "C"
else if (avg >= 60) grade = "D"
else grade = "F"
#increment counter for letter grade array
++class_grade[grade]
# print student name, average and letter grade
print $1, avg,grade
}
#print out class statistics
END {
#calculate class average
for (x = 1; x <= NR; x++)
class_avg_total += student_avg[x]
class_average = class_avg_total / NR
#determine how many above/bleow average
for (x =1; x <= NR; x++)
if (student_avg[x] >= class_average)
++above_average
else
++below_average
#print results
print ""
print "Class Average:",class_average
print "At or Above Average:",above_average
print "Below Average:",below_average
#print number of students per letter grade
for (lette_grade in class_grade)
print lette_grade ":",class_grade[lette_grade]| "sort"
}
$cat grade_student.statistics
myna 77 85 83 70 89 70
john 85 92 78 94 88 91
andrea 89 90 85 94 90 95
bush 98 98 89 96 96 92
jams 84 88 80 92 84 82
$awk -f grade_student.awk grade_student.statistics
myna 79 C
john 88 B
andrea 90.5 A
bush 94.8333 A
jams 85 B
Class Average: 87.4667
At or Above Average: 3
Below Average: 2
A: 2
B: 2
C: 1