How to initialize an array of arrays in awk?

前端 未结 5 1821
心在旅途
心在旅途 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:42

    A similar solution. SUBSEP=":" is not really needed, just set to any visible char for demo:

    awk 'BEGIN{SUBSEP=":"
    split("Red Green Blue",a); for(i in a) Colors[1,i]=a[i];
    split("Yellow Cyan Purple",a); for(i in a) Colors[2,i]=a[i];
    for(i in Colors) print i" => "Colors[i];}'
    

    Or a little bit more cryptic version:

    awk 'BEGIN{SUBSEP=":"
    split("Red Green Blue Yellow Cyan Purple",a); 
    for(i in a) Colors[int((i-1)/3)+1,(i-1)%3+1]=a[i];
    for(i in Colors) print i" => "Colors[i];}'
    

    Output:

    1:1 => Red
    1:2 => Green
    1:3 => Blue
    2:1 => Yellow
    2:2 => Cyan
    2:3 => Purple
    

提交回复
热议问题