User-Defined Functions
Example
$ Cat datafilenorthwest NW Joel Craig 3.0. 98 3 4 western WE Sharon Kelly 5.3. 97 5 23 southwest SW Chris Foster 2.7. 8 2 18 southern SO May Chin 5.1. 95 4 15 southeast SE Derek Johnson 4.0. 7 4 17 eastern EA Suan Beal 4.4. 84 5 20 northeast ne tj nickls 5.1. 94 3 13 north NO Val Shultz 4.5. 89 5 9 central CT Sheri Watson 5.7. 94 5 13 $ cat awk. scBEGIN {largest = O} {maximum = max ($5)} function max (num) {if (num> largest) {largest = num} return largest} END {print "The maximum is" maximum ". "} $ awk-f awk. SC datafi1eThe maximum is 5.7.
Description
1. the User-Defined variables are initialized to 0 in the BEGIN block.
2. When processing each row in the file, the $5 parameter is used to call function max and the return value is assigned to the variable.
Maximum.
3. Define the User-Defined Function max. The function statements must be enclosed in curly brackets. Each time a new record is read from the input file datafile, the script calls the max function.
4. Compare the values of num and largest, and return a large value.
5. The end of the Function Definition block.
6. The END Block prints the final value of maximum.