作業九: figure out the average for each user(awk programming)
與作業七相同, 但改用 awk 來作. input 的 data 中的 name 可能會重複出現.
$ cat ex9-k1
klim 10 20 milk 199 joe 20
# klim is appeared again!
oak 100 red 200 10 klim 30
joe 199 marry 20 julie 2000 #joe joe
$ ./ex9.awk < ex9-k1
klim = 20.00
milk = 199.00
oak = 100.00
red = 105.00
joe = 109.50
marry = 20.00
julie = 2000.00
$
解答:
#!/usr/bin/awk -f
BEGIN {
}
{
sub(/#.*/,"")
if ( $0 != "" ) {
for (i=1; i<=NF; i++) {
if ( $i ~ /[a-z]/ ) { # $1 is name
name=$i
}
else { # $1 is number
array[name]=array[name]+$i
num_count[name]=num_count[name]+1
}
} #for i END
} #if END
}
END {
for (i in array)
printf("%s = %.2f\n",i, array[i]/num_count[i])
}
執行結果:
沒有留言:
張貼留言