Asort (src, dest) to a multidimensional array

I am trying to use asort() (simply because) to copy the src array to the dest array, no problem:

 $ awk 'BEGIN { split("first;second;third",src,";") # make src array for testing asort(src, dest, "@ind_num_asc") # copy array to dest for(i in dest) print i, src[i], dest[i] # output }' 1 first first 2 second second 3 third third 

But is there a way to use a multidimensional array as a dest array? Sort of:

asort(src, dest[src[1]], "@ind_num_asc") # or dest[src[1]][]

(The former produces the second argument not an array , the last syntax error In reality, the first argument to split is $0 , and I'm trying to group the records.)

Of course, I could use a for loop, but my brain is stuck in testing this solution.

+5
source share
1 answer

You just need to create an array under dest[src[1]] so that gawk knows that dest[src[1]] is an array of arrays, not a default array of strings:

 $ cat tst.awk BEGIN { split("first;second;third",src,/;/) # make src array for testing asort(src, dest1d) # copy array to dest1d for(i in dest1d) print i, src[i], dest1d[i] # output print "" dest2d[src[1]][1] asort(src, dest2d[src[1]]) # copy array to dest2d for(i in dest2d) for (j in dest2d[i]) print i, j, dest2d[i][j] # output } $ gawk -f tst.awk 1 first first 2 second second 3 third third first 1 first first 2 second first 3 third 

It doesn't matter which index you specify for this initial submatrix, since it will be deleted using asort (). See the latest example at https://www.gnu.org/software/gawk/manual/gawk.html#Arrays-of-Arrays :

Recall that a reference to an uninitialized array element gives the value "", a null string. This is of one importance when you intend to use a subarray as an argument to a function, as illustrated by the following example:

 $ gawk 'BEGIN { split("abcd", b[1]); print b[1][1] }' error→ gawk: cmd. line:1: fatal: split: second argument is not an array 

A way around this is to first make b [1] be an array by creating an arbitrary index:

 $ gawk 'BEGIN { b[1][1] = ""; split("abcd", b[1]); print b[1][1] }' -| a 
+3
source

All Articles