I am looking for simple array definition on awk by simple example. How to define array and use the elements of the array on awk language?
3 Answers
Awk does not have arrays, but maps.
Like all variables in awk, there is no need to define it. It will happen when you first use it.
To assign an element of a map:
a[key] = value
To use an element:
print a[key]
To iterate:
for (i in a) {
print i, a[i]
}
If you use integers as keys, the map will be equivalent to an array.

- 32,226
- 12
- 81
- 108
Arrays in awk are associative types i.e. you can also use strings and not just numbers as keys to index the values.
a[1] = "abc" ## Valid.
a["x"] = "xyz" ## Also valid.
Accessing elements in an array can be done with i in a
where i
would get the key and a
is the referred array. Example:
#!/usr/bin/awk -f
BEGIN {
a[1] = "abc"
a["x"] = "xyz"
for (i in a) {
print a[i]
}
}
awk -f script.awk
would print:
xyz
abc
You may notice that the order of how the elements were accessed is not the same as how they were saved. This is because awk
can have different types of implementations when it comes to this.
If you want to be certain that elements would be accessed in order, you'd have to store them with numerical keys or indices instead:
#!/usr/bin/awk -f
BEGIN {
a[0] = "abc"
a[1] = "xyz"
for (i = 0; i in a; ++i) {
print a[i]
}
}
You can also configure the behaviour when using GNU's awk:
PROCINFO["sorted_in"]
If this element exists in PROCINFO, then its value controls the order in which array elements are traversed in for loops. Supported values are "@ind_str_asc", "@ind_num_asc", "@val_type_asc", "@val_str_asc", "@val_num_asc", "@ind_str_desc", "@ind_num_desc", "@val_type_desc", "@val_str_desc", "@val_num_desc", and "@unsorted". The value can also be the name of any comparison function defined as follows:
function cmp_func(i1, v1, i2, v2)
where i1 and i2 are the indices, and v1 and v2 are the corresponding values of the two elements being compared. It should return a number less than, equal to, or greater than 0, depending on how the elements of the array are to be ordered.

- 72,135
- 12
- 99
- 105