awk / gawk asorti() 问题

发布于 2024-09-06 15:15:20 字数 597 浏览 6 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

氛圍 2024-09-13 15:15:21

根据 gawk 手册:“一个重要方面关于数组要记住的是数组下标始终是字符串。

According to the gawk manual: "An important aspect about arrays to remember is that array subscripts are always strings."

往昔成烟 2024-09-13 15:15:21

我知道 gawk 3 有限制,但在 gawk 4 (至少在 4.1.1 上)这是微不足道的:

t=asorti(a, o, "@ind_num_asc");

I know there were limitations on gawk 3, but on gawk 4 (at least on 4.1.1) it's trivial:

t=asorti(a, o, "@ind_num_asc");
怀中猫帐中妖 2024-09-13 15:15:21

作为解决方法,您可以使用类似的方法(您可能需要调整填充):

gawk 'BEGIN { 
  a[1] = 6; a[2] = 7; a[3] = 8; a[21] = 9; a[123] = 10; 
  for (i in a) io[sprintf("%15s", i)] = a[i]
  t = asorti(io, o)
  for (i = 0; ++i <= t;) print i, o[i] + 0
    }'

使用 Gnu awk,您甚至可以保留原始键/索引:

WHINY_USERS=oops gawk 'BEGIN { 
  a[1]=6; a[2]=7; a[3]=8; a[21]=9; a[123]=10; 
  for (i in a) o[sprintf("%15s", i)] = a[i]
  for (i in o) print i + 0, o[i]
    }'

As a workaround you could use something like this (you may need to adjust the padding):

gawk 'BEGIN { 
  a[1] = 6; a[2] = 7; a[3] = 8; a[21] = 9; a[123] = 10; 
  for (i in a) io[sprintf("%15s", i)] = a[i]
  t = asorti(io, o)
  for (i = 0; ++i <= t;) print i, o[i] + 0
    }'

With Gnu awk you can even preserve the original keys/indexes:

WHINY_USERS=oops gawk 'BEGIN { 
  a[1]=6; a[2]=7; a[3]=8; a[21]=9; a[123]=10; 
  for (i in a) o[sprintf("%15s", i)] = a[i]
  for (i in o) print i + 0, o[i]
    }'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文