Search code examples
awkvariadic-functions

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)


Solution

  • There are no variadic functions in awk because they're not needed since you can just populate an array and pass that into a function:

    $ 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
    

    or just define the function with a bunch of dummy argument names as @triplee mentions.