How to initialize an array of arrays in awk?

前端 未结 5 1819
心在旅途
心在旅途 2020-12-14 06:42

Is it possible to initialize an array like this in AWK ?

Colors[1] = (\"Red\", \"Green\", \"Blue\")
Colors[2] = (\"Yellow\", \"Cyan\", \"Purple\")

5条回答
  •  太阳男子
    2020-12-14 07:40

    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/null
    Colours[1,1] = Red
    Colours[1,2] = Green
    Colours[1,3] = Blue
    Colours[2,1] = Yellow
    Colours[2,2] = Cyan
    Colours[2,3] = Purple
    $
    

提交回复
热议问题