17

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?

28

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.

  • The alternative split solution was helpful. It was a surprise to find SCO Openserver 5.0.7 awk calls delete array a syntax error though the man page says the subscript is optional. $ awk 'BEGIN { A[1] = 0; delete A; }' awk: Syntax error at line 1 of program << BEGIN { A[1] = 0; de ... >> context is BEGIN { A[1] = 0; delete >>> A; <<< awk: illegal statement at line 1 of program << BEGIN { A[1] = 0; de ... >> It was more surprising to find that delete array[subscript], while not shown as an error, also did not work, and many variants on array[subscript] = "" were all equally ineffective. – kbulgrien Apr 24 '18 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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