Download Introduction to Operating Systems Abstractions Using Plan 9 from
Transcript
- 218 program computes the total sum and average for a list of numbers.
; seq 5000 | awk ’
;; BEGIN { sum=0.0 }
;; { sum += $1 }
;; END { print sum, sum/NR }
;; ’
12502500 2500.5
Remember that ;; is printed by the shell, and not part of the AWK program. We have used seq
to print some numbers to test our script. And, as you can see, the syntax for actions is similar to
that of C. But note that a statement is also delimited by a newline or a closed brace, and we do not
need to add semicolons to terminate them. What did this program do? Before even processing the
first line, the action of BEGIN was executed. This sets the variable sum to 0.0. Because the
value is a floating point number, the variable has that type. Then, field after field, the action without a pattern was executed, updating sum. At last, the action for END printed the outcome. By
dividing the number of records (i.e., of lines or numbers) we compute the average.
As an aside, it can be funny to note that there are many AWK programs with only an action
for BEGIN. That is a trick played to exploit this language to evaluate complex expressions from
the shell. Another contender for hoc.
; awk ’BEGIN {print sqrt(2) * log(4.3)}’
2.06279
; awk ’BEGIN {PI=3.1415926; print PI * 3.7^2}’
43.0084
This program is closer to what we want to do to determine which process is the biggest one. It
computes the maximum of a list of numbers.
; seq 5000 | awk ’
;; BEGIN { max=0 }
;; {
if (max < $1)
;;
max=$1
;; }
;; END { print max }
;; ’
5000
Correct?
This time, the action for all the records in the input updates max, to keep track of the biggest
value. Because max was first used in a context requiring an integer (assigned 0), it is integer.
Let’s try now our real task.
; ps | awk ’
;; BEGIN { max=0 }
;; {
if (max < $5)
;;
max=$5
;; }
;; END { print max }
;; ’
9412K
Wrong! because it should have said...
; ps | sort +4r | awk ’{print $5; exit}’
11844K
What happens is that 11844K is not bigger than 9412K. Not as a string.
; awk ’BEGIN { if ("11844K" > "9412K") print "bigger" }’
;
Watch out for this kind of mistake. It is common, as a side effect of AWK efforts to simplify
things for you, by trying to infer and declare variable types as you use them. We must force