AWK函数带有可变数量的参数



如何定义具有可变数量参数的AWK函数?我可以通过命令行参数来模拟这个:

awk 'BEGIN {for (i in ARGV) printf ARGV[i]" "}' 1 2 3

但CCD_ 1不是函数(在AWK中(。

目前我正在使用MAWK(但如果有帮助的话,可能会切换到GAWK(

注意:我不能透露任务(这是一个我应该自己解决的练习(

awk中没有可变函数,因为不需要它们,因为您只需填充一个数组并将其传递到函数中:

$ cat tst.awk
BEGIN {
split("foo 17 bar",a)
foo(a)
}
function foo(arr,       i,n) {
n = length(arr)     # or loop incrementing n if length(arr) unsupported
for (i=1; i<=n; i++) {
printf "%s%s", arr[i], (i<n ? OFS : ORS)
}
}
$ awk -f tst.awk
foo 17 bar

或者只是用@triple提到的一堆伪参数名称来定义函数。

根据https://rosettacode.org/wiki/Variadic_function您可以定义一个参数比传入参数多的函数;你省略的那些会变成空的。

从你的例子中还不清楚你到底在努力实现什么,但这就是你实际问题的答案。

$ awk 'function handlemany(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth) {
>   print first, second, third, fourth, fifth, sixt, seventh, eighth, ninth, tenth, eleventh, twelfth
> }
> BEGIN { handlemany("one", "two", "three") }'
one two three       

当然,这并不理想,但在Awk语言中不支持适当的变差函数/varargs

最新更新