Delete an array in awk

In awk, I can clear an array with a loop, making it an empty array, which is equivalent to deleting it.

for (key in array) delete array[key];

Is there a simpler way? Can I completely delete an array, so that the variable name can be re-used for a scalar?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The syntax

delete array

is not in current versions in POSIX, but it is supported by virtually all existing implementations (including the original awk, GNU, mawk, and BusyBox). It will be added in a future version of POSIX (see defect 0000544).

An alternate way to clear all array elements, which is both portable and standard-compliant, and which is an expression rather than a statement, is to rely on split deleting all existing elements:

split("", array)

All of these, including delete array, leave the variable marked as being an array variable in the original awk, in GNU awk and in mawk (but not in BusyBox awk). As far as I know, once a variable has been used as an array, there is no way to use it as a scalar variable.

Method 2

Not sure why it’d be a good idea but if you want to use the same name as both an array and a scalar, you can do that if you don’t use them in the same scope, e.g.:

$ cat tst.awk
BEGIN {
    fooIsArray()
    foo = 17
    print "foo is a scalar:", foo
}

function fooIsArray(    foo) {
    foo[1] = "bar"
    print "foo is an array:", foo[1]
}
$ awk -f tst.awk
foo is an array: bar
foo is a scalar: 17

In the above we’re making foo[] a function-local variable by declaring it as an unused argument to the function fooIsArray() and so it’s unrelated to the global scalar variable foo used elsewhere in the script and the contents of the array foo[] will be deleted on return from the function fooIsArray().


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x