Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to append an item to an array in awk without specifying an index?

Tags:

I realize that awk has associative arrays, but I wonder if there is an awk equivalent to this:

http://php.net/manual/en/function.array-push.php

The obvious workaround is to just say:

array[$new_element] = $new_element 

However, this seems less readable and more hackish than it needs to be.

like image 670
merlin2011 Avatar asked May 25 '12 17:05

merlin2011


People also ask

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.

Can you use .append on an array?

We can create an array using the Array module and then apply the append() function to add elements to it.

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.

What is array in awk?

8 Arrays in awk An array is a table of values called elements. The elements of an array are distinguished by their indices. Indices may be either numbers or strings.


1 Answers

I don't think an array length is immediately available in awk (at least not in the versions I fiddle around with). But you could simply maintain the length and then do something like this:

array[arraylen++] = $0; 

And then access the elements it via the same integer values:

for ( i = 0; i < arraylen; i++ )    print array[i]; 
like image 190
Mark Wilkins Avatar answered Sep 19 '22 06:09

Mark Wilkins