awkassociative-arraygawk

Declaring all elements of an associative array in a single statement - AWK


I am fairly new to awk and am trying to figure out how to declare all elements of an associative array in one go. For example, if I wanted to declare an associative array in Python (which is effectively the dictionary) I would do this:

numbers = {'uno': 1, 'sero': 0}

Now, in awk is it possible to convert the two lines of code below into one?

 numbers["uno"] = 1
 numbers["sero"] = 0

Solution

  • AWK doesn't have array literals as far as I know, but this script demonstrates something you can do to get close:

    BEGIN {
        split("uno|1|sero|0",a,"|");
        for (i = 1; i < 4; i += 2) {b[a[i]] = a[i+1];}
    }
    END {
        print b["sero"];
        print b["uno"];
    }
    

    Of course, you can always make a function that could be called like

    newarray("uno", 1, "sero", 0);
    

    or like

    newarray("uno|1|sero|0");