awk / gawk asorti() 问题
我在 gawk 的 asorti 函数上遇到了以下问题:
gawk 'BEGIN{ \
a[1]=6; \
a[2]=7; \
a[3]=8; \
a[21]=9; \
a[123]=10; \
t=asorti(a, o); \
for (i=1; i<=t; i++) { \
print i,o[i]; \
} \
}'
结果是:
1 1
2 123
3 2
4 21
5 3
所以 awk 非常清楚,按字典顺序排序索引,但 awk 的文档说 (asort(s[, d])):
“s 的内容使用 gawk 比较值的正常规则进行排序...”
但是,当我将索引本身复制到临时数组中,并使用 asort() 对新数组进行排序时,
似乎没问题(使用类似的东西):
j=1; for(e in a) { temp[j++] = e; }
我是吗?做错了,还是 gawk 的 asorti() 有问题?
I've got following problem with gawk's asorti function:
gawk 'BEGIN{ \
a[1]=6; \
a[2]=7; \
a[3]=8; \
a[21]=9; \
a[123]=10; \
t=asorti(a, o); \
for (i=1; i<=t; i++) { \
print i,o[i]; \
} \
}'
The result is:
1 1
2 123
3 2
4 21
5 3
So it's pretty clear awk, sorted indices in lexicographical order, but awk's doc says (asort(s[, d])):
"The contents of s are sorted using gawk’s normal rules for comparing values..."
However, when I copy indices itself into temp array, and sort that new array using asort(),
it seems ok (using something like):
j=1; for(e in a) { temp[j++] = e; }
Am I DOIN-IT-WRONG, or is it problem with gawk's asorti() ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 gawk 手册:“一个重要方面关于数组要记住的是数组下标始终是字符串。”
According to the gawk manual: "An important aspect about arrays to remember is that array subscripts are always strings."
我知道 gawk 3 有限制,但在 gawk 4 (至少在 4.1.1 上)这是微不足道的:
I know there were limitations on gawk 3, but on gawk 4 (at least on 4.1.1) it's trivial:
作为解决方法,您可以使用类似的方法(您可能需要调整填充):
使用 Gnu awk,您甚至可以保留原始键/索引:
As a workaround you could use something like this (you may need to adjust the padding):
With Gnu awk you can even preserve the original keys/indexes: