数组 – 为什么awk似乎随机化数组?

数组 – 为什么awk似乎随机化数组?,第1张

概述如果你看看这个awk测试的输出,你会看到awk中的数组似乎是以某种随机模式打印的.对于相同数量的输入,它似乎是相同的顺序.它为什么这样做? 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 four5 five6 six1 one 如果你看看这个awk测试的输出,你会看到awk中的数组似乎是以某种随机模式打印的.对于相同数量的输入,它似乎是相同的顺序.它为什么这样做?

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 four5 five6 six1 one2 two3 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 1SAF4 1C2618 1SAK5 1DT719 1SAL6 1GZH7 1H268 1HS59 1JsP10 1KZY20 1TSR11 1MA321 1TUP12 1olG22 1Uol13 1olH23 1XQH14 1PES1 P0463724 1YC515 1PET2 1A1U25 1YCQ16 1SAE3 1AIE

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

解决方法 在引用for(数组中的值)语法时,从GNU Awk用户指南中的 8. Arrays in awk –> 8.5 Scanning All Elements of an Array开始:

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.

因此,如果要按照存储顺序打印数组,则必须使用经典的for循环:

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 P046372 1A1U3 1AIE4 1C265 1DT76 1GZH7 1H268 1HS59 1JsP10 1KZY11 1MA312 1olG13 1olH14 1PES15 1PET16 1SAE17 1SAF18 1SAK19 1SAL20 1TSR21 1TUP22 1Uol23 1XQH24 1YC525 1YCQ
总结

以上是内存溢出为你收集整理的数组 – 为什么awk似乎随机化数组?全部内容,希望文章能够帮你解决数组 – 为什么awk似乎随机化数组?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1029002.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存