How to initialize an array of arrays in awk? How to initialize an array of arrays in awk? arrays arrays

How to initialize an array of arrays in awk?


If you have GNU awk, you can use a true multidimensional array. Although this answer uses the split() function, it most certainly doesn't abuse it. Run like:

awk -f script.awk

Contents of script.awk:

BEGIN {    x=SUBSEP    a="Red" x "Green" x "Blue"    b="Yellow" x "Cyan" x "Purple"    Colors[1][0] = ""    Colors[2][0] = ""    split(a, Colors[1], x)    split(b, Colors[2], x)    print Colors[2][3]}

Results:

Purple


You can create a 2-dimensional array easily enough. What you can't do, AFAIK, is initialize it in a single operation. As dmckee hints in a comment, one of the reasons for not being able to initialize an array is that there is no restriction on the types of the subscripts, and hence no requirement that they are pure numeric. You can do multiple assignments as in the script below. The subscripts are formally separated by an obscure character designated by the variable SUBSEP, with default value 034 (U+001C, FILE SEPARATOR). Clearly, if one of the indexes contains this character, confusion will follow (but when was the last time you used that character in a string?).

BEGIN {    Colours[1,1] = "Red"    Colours[1,2] = "Green"    Colours[1,3] = "Blue"    Colours[2,1] = "Yellow"    Colours[2,2] = "Cyan"    Colours[2,3] = "Purple"}END {    for (i = 1; i <= 2; i++)        for (j = 1; j <= 3; j++)            printf "Colours[%d,%d] = %s\n", i, j, Colours[i,j];}

Example run:

$ awk -f so14063783.awk /dev/nullColours[1,1] = RedColours[1,2] = GreenColours[1,3] = BlueColours[2,1] = YellowColours[2,2] = CyanColours[2,3] = Purple$


Thanks for the answers.Anyways, for those who want to initialize unidimensional arrays, here is an example:

SColors = "Red_Green_Blue"split(SColors, Colors, "_")print Colors[1] " - " Colors[2] " - " Colors[3]