awk PROCINFO["sorted_in"] Multidimensional array sorting problem

Viewed 349
[root@rocky ~]# cat c
a b 1
a c 4
a r 6
a t 2
b a 89
b c 76
a d 45
b z 9
[root@rocky ~]# awk '{a[$1][$2]=$3}END{PROCINFO["sorted_in"]="@val_num_asc";for(i in a){for(x in a[i])print i,x,a[i][x]}}' c
a b 1
a t 2
a c 4
a r 6
a d 45
b z 9
b c 76
b a 89
[root@rocky ~]# awk '{a[$2]=$3}END{PROCINFO["sorted_in"]="@val_num_asc";for(i in a)print i,a[i]}' c
b 1
t 2
r 6
z 9
d 45
c 76
a 89
[root@rocky ~]# awk '{a[$2]=$3}END{PROCINFO["sorted_in"]="@val_num_desc";for(i in a)print i,a[i]}' c
a 89
c 76
d 45
z 9
r 6
t 2
b 1
[root@rocky ~]# awk '{a[$1][$2]=$3}END{PROCINFO["sorted_in"]="@val_num_desc";for(i in a){for(x in a[i])print i,x,a[i][x]}}' c
a d 45
a r 6
a c 4
a t 2
a b 1
b a 89
b c 76
b z 9
[root@rocky ~]# awk --version
GNU Awk 4.2.1, API: 2.0 (GNU MPFR 3.1.6-p2, GNU MP 6.1.2)

There is a problem with the sorting of multidimensional arrays using PROCINFO["sorted_in"]="@val_num_asc" or PROCINFO["sorted_in"]="@val_num_desc", and there is no real sorting. There is no problem with one-dimensional arrays. What is the problem? Is it because it does not support multidimensional arrays?

1 Answers
awk '{a[$1][$2]=$3}END{PROCINFO["sorted_in"]="@val_num_asc";for(i in a){for(x in a[i])print i,x,a[i][x]}}' c

a b 1
a t 2
a c 4
a r 6
a d 45
b z 9
b c 76
b a 89

This is not a bug, this is how it is supposed to work. Look closely, you are using a nested loop here.

for(i in a)

This is outer loop that will iterate through values a and b in 2 iterations.

for(x in a[i])

This is inner loop that will iterate through values of for a,[$2] first and b,[$2] second time.

@val_num_asc will sort values numerically in ascending order as per the value which is $3. If you look closely printed values 1,2,4,6,45 for $1=a are numerically sorted as per the value and so are 9,76,89 for $1=b.


If you want sorted output using awk then use this suggested workaround:

awk '{a[$1 OFS $2]=$3} END {PROCINFO["sorted_in"]="@val_num_asc"; for(x in a) print x, a[x]}' c

a b 1
a t 2
a c 4
a r 6
b z 9
a d 45
b c 76
b a 89
Related