Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 9 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.