I googled it and find out that after AWK 4.0 we can print an array in defined order by putting PROCINFO["sorted_in"] command right before for loop. For example
PROCINFO["sorted_in"] = "@ind_num_asc"
for( i in array)
print i, array[i]
In AWK 4.0.2, it works. However, I tried it in AWK 3.1.3 environment, it did not work. Does this early version of AWK do not support this function? How to achieve this goal in AWK 3.1.3?
In awk , you don't need to specify the size of an array before you start to use it. Additionally, any number or string in awk may be used as an array index, not just consecutive integers. In most other languages, you have to declare an array and specify how many elements or components it contains.
To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.
AWK has associative arrays and one of the best thing about it is – the indexes need not to be continuous set of number; you can use either string or number as an array index. Also, there is no need to declare the size of an array in advance – arrays can expand/shrink at runtime.
The awk language provides one-dimensional arrays for storing groups of related strings or numbers. Every awk array must have a name. Array names have the same syntax as variable names; any valid variable name would also be a valid array name.
Just keep a second array order
with numerical indices and the keys for the first array as the values. You can then iterate through order
in sequence and look up the values of array
:
for (i = 1; i < length(order); i++) {
print order[i], array[order[i]]
}
When building order
, you may want to check whether the key is already present in array
, to prevent the keys of array
being shown multiple times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With