awk

Do we really have to copy the whole array to make it an element of an other array with GNU awk?


I would like to assign an array as an array element, with GNU awk.

Here's a non-working example illustrating the problem:

echo X1 X2 X3 X4 |
awk '
    function dummy_split(arr) { split($0, arr) }

    {
        dummy_split(a)
        multidimarray["ID" NR] = a;
    }
'
awk: cmd. line:5: (FILENAME=- FNR=1) fatal: attempt to use array `a' in a scalar context

What I'm trying to achieve in to "define" multidimarray["ID1"] as follows:

multidimarray["ID1"][1] = "X1"
multidimarray["ID1"][2] = "X2"
multidimarray["ID1"][3] = "X3"
multidimarray["ID1"][4] = "X4"

Is there any GNU awk functionality that would make it simpler than copying manually every key+element of a using a for loop?


Solution

  • If your gawk is new enough to support array of arrays:

    $ echo X1 X2 X3 X4 |
      gawk '
        function dummy_split(arr) { split($0, arr) }
    
        {
          multidimarray["ID" NR][1];
          dummy_split(multidimarray["ID" NR]);
    
          for (k in multidimarray["ID" NR])
            printf "multidmarray[\"ID%d\"][%s] = %s\n", NR, k, multidimarray["ID"NR][k]  
        }
      '
    multidmarray["ID1"][1] = X1
    multidmarray["ID1"][2] = X2
    multidmarray["ID1"][3] = X3
    multidmarray["ID1"][4] = X4
    

    However, since gawk arrays are jagged, to copy elements from an existing array into a new one probably will require copying the elements individually. See for example, @EdMorton's copy_array

    See Ed's code for explanation of the multidim["ID"NR][1] line.