举例来说明
$
cat datafile
northwest 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 Nichols 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. sc
BEGIN { 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 datafi1e
The maximum is 5.7.
northwest 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 Nichols 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. sc
BEGIN { 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 datafi1e
The maximum is 5.7.
说明
1.用户自定义变量在BEGIN块中被初始化为0。
2.处理文件中的每一行时,都以$5为参数调用函数max,并将其返回值赋给变量
maximum。
3.定义用户自定义函数max,函数的语句必须括在花括号中。每次从输入文件datafile中读取新的记录后,脚本都会调用max函数。
4. 比较num和largest的值,返回其中较大的值。
5. 函数定义块结尾。
6. END块打印maximum最终的值。