How to print an array in defined order in AWK 3.1.3

awk
10,811

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.

Share:
10,811
coinsyx
Author by

coinsyx

Updated on June 20, 2022

Comments

  • coinsyx
    coinsyx almost 2 years

    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?

    • Serve Laurijssen
      Serve Laurijssen about 11 years
      check out asort/asorti for sorting an array
    • Ed Morton
      Ed Morton about 11 years
      No, non-GNU awks and older versions of gawk do not support this functionality. Clarify "defined order" and "this goal". Are you looking to print an array in a specific order and, if so, what is the order (first in or numerical sort or alphabetical sort or ...)? Alternatively are you looking for a mechanism to define different orders of printing arrays like you show in your example by populating PROCINFO[]?
  • 0zkr PM
    0zkr PM almost 9 years
    There is no "length" function in 3.1.3.See Mr. Ventimiglia's function (with my extensión) at stackoverflow.com/questions/9351902/… or just keep the last index used at the creation of "order".