Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK function w/ a variable number of arguments

How to define an AWK function w/ a variable number of arguments? I can emulate this w/ command line arguments:

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

but BEGIN {for (i in ARGV) printf ARGV[i]" "} isn't a function (in AWK).

Currently I'm using MAWK (but can probably switch to GAWK if it would help)

NOTE: I cannot reveal the task (it's an exercise which I'm supposed to solve by myself)

like image 383
jaam Avatar asked Aug 28 '26 05:08

jaam


1 Answers

As per https://rosettacode.org/wiki/Variadic_function you can define a function with more arguments than you pass in; the ones you omit will come out as empty.

It's not clear from your example what you are actually trying to accomplish, but this is the answer to your actual question.

$ 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       

This is less than ideal, of course, but there is no support for proper variadic functions / varargs in the Awk language.

like image 156
tripleee Avatar answered Aug 30 '26 02:08

tripleee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!