在awk中排序哈希/数组
时间:2020-03-06 14:28:19 来源:igfitidea点击:
有没有一种简单的方法可以在awk中执行以下任何操作?
- 按数据对数组/哈希排序
- 按字符串键对哈希进行排序
解决方案
这是其他人对非常相似的问题的回答:
http://www.computing.net/answers/unix/urgent-help-with-sorting-in-awk/4442.html
应该是这样的:
gawk 'BEGIN {c=1} { array[c] = sprintf ("%s %s", , ); c++ } END { asort(array); for (x=1;x<c;x++) { print array[x] } }'
请注意,我使用了" gawk"。如果要进行内置排序,请使用gawk。
该示例接受键值对的"以空格分隔"的输入,并根据第二个值对它们进行排序(当然,它以值/键格式将它们打印出来,但是我们可以看到我在做什么。)
为了对gawk中现存的数组执行此操作,我们将使用类似的方法。
如果使用awk或者mawk,则必须使用手册页中提供的许多排序功能之一来完成排序。
From the gawk manpage: All arrays in AWK are associative, i.e. indexed by string values. The special operator in may be used in an if or while statement to see if an array has an index consisting of a particular value. if (val in array) print array[val] If the array has multiple subscripts, use (i, j) in array.