views:

2428

answers:

1

Is there an easy way to do any of the following things in awk?

  • Sorting array/hash by it's data
  • Sorting a hash by it's string key
+1  A: 

Here's someone else's answer to a very similar problem: http://www.computing.net/answers/unix/urgent-help-with-sorting-in-awk/4442.html

Which is supposed to be something like this: gawk 'BEGIN {c=1} { array[c] = sprintf ("%s %s", $2, $1); c++ } END { asort(array); for (x=1;x<c;x++) { print array[x] } }'

Note that I used 'gawk'. If you want built-in sorting, use gawk.

That example takes a 'space-separated' input of key value pairs and sorts them based on the second value (of course it prints them out in value/key format, but you see what I'm doing there.)

In order to do that to an array extant in gawk, you'd use something similar.

If using awk or mawk, you'll have to use one of the many sort functions available in man pages to accomplish the sort.

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.

Chris
That took me a little bit, I've done something like this before, but it was a long time ago. The fun parts would be separating input by a regex, then sorting it.
Chris
thanks. Unfortunately I use nawk, wich does not have asort.
lamcro