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