Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an array in defined order in AWK 3.1.3

Tags:

awk

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?

like image 949
coinsyx Avatar asked Apr 18 '13 06:04

coinsyx


People also ask

How do you declare an array in awk?

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.

How to use awk to print lines?

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.

How arrays are processed using awk?

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.

Does awk have arrays?

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.


1 Answers

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.

like image 106
Michael J. Barber Avatar answered Oct 12 '22 23:10

Michael J. Barber