96. 用户自定义函数
awk 允许您定义用户定义的函数。 当您编写大量 awk 代码并最终每次都重复某些代码片段时,这非常有用。 这些部分可以适合用户定义的函数。
语法:
function fn-name(parameters)
{
function-body
}
在上面的语法中:
fn-name
是函数名称:就像 awk 变量一样,awk 用户定义的函数名称应以字母开头。 其余字符可以是数字、字母字符或下划线。 关键字不能用作函数名称。parameters
:多个参数以逗号分隔。 您还可以创建不带任何参数的用户定义函数。function-body
:一个或多个awk 语句。
如果您已经在 awk 程序中使用了变量的名称,则不能对用户定义的函数使用相同的名称。
以下示例创建一个名为 discount
的简单用户定义函数,该函数提供指定百分比的价格折扣。 例如,discount(10)
提供 10% 的价格折扣。
对于任何数量 <= 10
的商品,给予 10% 的折扣,否则给予 50% 的折扣。
$ cat function.awk
BEGIN {
FS=","
OFS=","
}
{
if ($5 <= 10)
print $1,$2,$3,discount(10),$5
else
print $1,$2,$3,discount(50),$5
}
function discount(percentage)
{
return $4 - ($4*percentage/100)
}
$ awk -f function.awk items.txt
101,HD Camcorder,Video,189,10
102,Refrigerator,Appliance,765,2
103,MP3 Player,Audio,135,15
104,Tennis Racket,Sports,95,20
105,Laser Printer,Office,427.5,5
创建自定义函数的另一个好用途是打印调试消息。
以下是一个简单的 mydebug 函数:
$ cat function-debug.awk
{
i=2; total=0;
while (i <= NF) {
mydebug("quantity is " $i);
total = total + $i;
i++;
}
print "Item", $1, ":", total, "quantities sold";
}
function mydebug ( message ) {
printf("DEBUG[%d]>%s\n", NR, message )
}
$ awk -f function-debug.awk items-sold.txt
DEBUG[1]>quantity is 2
DEBUG[1]>quantity is 10
DEBUG[1]>quantity is 5
DEBUG[1]>quantity is 8
DEBUG[1]>quantity is 10
DEBUG[1]>quantity is 12
Item 101 : 47 quantities sold
DEBUG[2]>quantity is 0
DEBUG[2]>quantity is 1
DEBUG[2]>quantity is 4
DEBUG[2]>quantity is 3
DEBUG[2]>quantity is 0
DEBUG[2]>quantity is 2
Item 102 : 10 quantities sold