So we've created an array and displayed the contents, only to discover they aren't even in the same order we started with!
What to do? awk has a built-in function for this called asort.
print "\nSorted by value ...";
# empty the awry
for (i in awry) {
delete awry[i]
}
# start over
awry["three"] = "blueberry"
awry["two"] = "cherry"
awry["seven"] = "pineapple"
awry["nineteen"] = "orange"
awry["five"] = "grape"
awry["thirteen"] = "strawberry"
awry["four"] = "apple"
awry["1"] = "pear"
asort(awry)
for (i in awry) {
print i " : " awry[i]
}
That code should result in this:
Sorted by value ... 1 : apple 2 : blueberry 3 : cherry 4 : grape 5 : orange 6 : pear 7 : pineapple 8 : strawberry
That looks different than our first attempt on the previous page.
It is sorting the 'values' in the 'key - value' pairs.
Another built-in sort function is asorti, which does sort by the index.
# empty the array
for (i in awry) {
delete awry[i]
}
# start over
awry["three"] = "blueberry"
awry["two"] = "cherry"
awry["seven"] = "pineapple"
awry["nineteen"] = "orange"
awry["five"] = "grape"
awry["thirteen"] = "strawberry"
awry["four"] = "apple"
awry["1"] = "pear"
k=asorti(awry)
j=split($0,awry," ")
print "There are $k elements in the array\n"
asorti(awry,sawry)
for (i = 1; i<=k; i++) {
print (i " : " awry[sawry[i]] )
}
Now we get the array sorted by the index ...
Sorted by index ... There are 8 elements in the array 1 : 1 2 : five 3 : four 4 : nineteen 5 : seven 6 : thirteen 7 : three 8 : two
You will notice the indices have changed from the original - we've lost the string indices!
Subscripts for awk arrays are always strings.
awk has interesting conversion rules when dealing with strings as indices.
For asort(), gawk sorts the values of source and replaces the indices of the sorted values of source with sequential integers starting with one.
We've also shown you 2 new features in this code: how to empty an array, and how to get the number of elements in an array.
Emptying an array is not the same as deleting an array
split("",array)
To get the number of elements in the array, we get the return value of asorti. Actually it returns the index of the last element, so in this case it works as the number of elements.
k=asorti(awry)