加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

数组 – asort(src,dest)到多维数组

发布时间:2020-12-31 01:38:08 所属栏目:Linux 来源:网络整理
导读:我试图滥用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

我试图滥用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]] []

(前者产生的第二个参数不是数组,后面的语法错误
实际上,拆分的第一个参数是0美元,而我正试图将记录分组.)

当然我可以使用for循环,但我的大脑仍然坚持测试这个解决方案.

解决方法

你只需要在dest [src [1]]下创建一个数组,所以gawk知道dest [src [1]]是一个数组数组而不是默认的字符串数组:
$cat tst.awk
BEGIN {
    split("first;second;third",/;/) # make src array for testing

    asort(src,dest1d)              # copy array to dest1d
    for(i in dest1d)
        print 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:

06001

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

06002

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读