arrays - asort(src,dest) 到多维数组

标签 arrays sorting multidimensional-array awk gawk

我试图滥用asort()(只是因为)将数组src复制到数组dest,没有问题:

$ 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

但是有没有办法使用多维数组作为 dest 数组?像这样的东西:

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

(前者产生第二个参数不是数组,后者语法错误 实际上,split 的第一个参数是 $0,我正在尝试对记录进行分组。)

当然,我可以使用 for 循环,但我的大脑一直在测试这个解决方案。

最佳答案

你只需要先在 dest[src[1]] 下创建一个数组,这样 gawk 就知道 dest[src[1]] 是一个数组的数组,而不是比默认的字符串数组:

$ 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

给初始子数组指定什么索引并不重要,因为它会被 asort() 删除。请参阅 https://www.gnu.org/software/gawk/manual/gawk.html#Arrays-of-Arrays 下的最后一个示例:

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

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

The way to work around this is to first force b[1] to be an array by creating an arbitrary index:

$ gawk 'BEGIN { b[1][1] = ""; split("a b c d", b[1]); print b[1][1] }'
-| a

关于arrays - asort(src,dest) 到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39288847/

相关文章:

c - 排序 argv 插入随机数

javascript - Jquery UI 可排序更改无法正常工作

python - 从对象数组中提取的有效方法

android - 将字节数组转换为pdf文件然后保存

C++:检查所有数组元素是否相等的最快方法

arrays - 将二叉树展平为数组 : Is there a way to find a node's index in the array when traversing depth-first?

php - 如何从 foreach 循环创建这个多维数组?

java - 使用 Jackson 将 Json 数组拆分为单个 Json 元素

java - 数组排序后项目消失

arrays - N 维数组的实际使用,其中 (N>3)