为什么AWK似乎随机数组? [英] Why does awk seem to randomize the array?

查看:134
本文介绍了为什么AWK似乎随机数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你看一下这个输出 AWK 测试,可以看到阵列 AWK 似乎在一些随机图案进行打印。这似乎是在相同的顺序为相同数量的输入。它为什么这样做?

If you look at output of this awk test, you see that array in awk seems to be printed at some random pattern. It seems to be in same order for same number of input. Why does it do so?

echo "one two three four five six" | awk '{for (i=1;i<=NF;i++) a[i]=$i} END {for (j in a) print j,a[j]}'
4 four
5 five
6 six
1 one
2 two
3 three

echo "P04637 1A1U 1AIE 1C26 1DT7 1GZH 1H26 1HS5 1JSP 1KZY 1MA3 1OLG 1OLH 1PES 1PET 1SAE 1SAF 1SAK 1SAL 1TSR 1TUP 1UOL 1XQH 1YC5 1YCQ" | awk '{for (i=1;i<=NF;i++) a[i]=$i} END {for (j in a) print j,a[j]}'
17 1SAF
4 1C26
18 1SAK
5 1DT7
19 1SAL
6 1GZH
7 1H26
8 1HS5
9 1JSP
10 1KZY
20 1TSR
11 1MA3
21 1TUP
12 1OLG
22 1UOL
13 1OLH
23 1XQH
14 1PES
1 P04637
24 1YC5
15 1PET
2 1A1U
25 1YCQ
16 1SAE
3 1AIE

为什么它这样做,是有规则吗?

Why does it do so, is there rule for this?

推荐答案

从的 8。在awk数组 - >参照为(以数组值),当GNUAwk用户指南中的数组的8.5扫描所有元素语法:

From 8. Arrays in awk --> 8.5 Scanning All Elements of an Array in the GNU Awk user's guide when referring to the for (value in array) syntax:

,其中所述阵列的元件由此访问的顺序
  声明是由阵列的内部结构确定
  AWK内和元素不能被控制或改变。这可以导致
  到的问题,如果新的元件用在语句添加到阵列
  循环体;它不是predictable与否的for循环会
  达到这些目标。同样的,不断变化的内循环VAR可能产生
  奇怪的结果。这是最好避免这样的事情。

The order in which elements of the array are accessed by this statement is determined by the internal arrangement of the array elements within awk and cannot be controlled or changed. This can lead to problems if new elements are added to array by statements in the loop body; it is not predictable whether or not the for loop will reach them. Similarly, changing var inside the loop may produce strange results. It is best to avoid such things.

所以,如果你要打印你存放的顺序排列,那么你必须使用传统的循环:


So if you want to print the array in the order you store it, then you have to use the classical for loop:

for (j=1; j<=NF; j++) print j,a[j]

示例:

$ awk '{for (i=1;i<=NF;i++) a[i]=$i} END {for (j=1; j<=NF; j++) print j,a[j]}' <<< "P04637 1A1U 1AIE 1C26 1DT7 1GZH 1H26 1HS5 1JSP 1KZY 1MA3 1OLG 1OLH 1PES 1PET 1SAE 1SAF 1SAK 1SAL 1TSR 1TUP 1UOL 1XQH 1YC5 1YCQ"
1 P04637
2 1A1U
3 1AIE
4 1C26
5 1DT7
6 1GZH
7 1H26
8 1HS5
9 1JSP
10 1KZY
11 1MA3
12 1OLG
13 1OLH
14 1PES
15 1PET
16 1SAE
17 1SAF
18 1SAK
19 1SAL
20 1TSR
21 1TUP
22 1UOL
23 1XQH
24 1YC5
25 1YCQ

这篇关于为什么AWK似乎随机数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆