Listing 3
BEGIN {
# (1)
FCOUNT=0
OCOUNT=0
VCOUNT=0
COUNT=0
SHORTS=0
ERRORS=0
printf "Parsing inventory file \"%s\"\n",
FILENAME
print
"=================================================="
}
{
# (2)
if(length($0) == 0) next
# (3)
if(NF != 3) {
printf "Bad data encountered: %s\n", $0
++ERRORS
next
}
# (4)
++COUNT
# (5)
if($1 == "fruit") {
++FCOUNT
}
else if($1 == "vegetable") {
++VCOUNT
}
else {
++OCOUNT
}
# (6)
# if inventory < 5, flag it as a shortage
if($3 < 5) {
++SHORTS
printf "Short on %s: %d left\n", $2, $3
}
}
END {
# (7)
print
"================================================="
printf "%d out of %d entries were of type %s.\n",
FCOUNT, COUNT, "Fruit"
printf "%d out of %d entries were of type %s.\n",
VCOUNT, COUNT, "Vegetable"
printf "%d out of %d entries were of type %s.\n",
OCOUNT, COUNT, "Other"
print ""
printf
"%d out of %d entries were flagged as bad data.\n",
ERRORS, COUNT,<\n>
printf
"%d out of %d entries were flagged in short supply.\n",
SHORTS, COUNT
}
Copyright © 1994 - 2018 Linux Journal. All rights reserved.