Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an array in awk

Tags:

awk

I have used awk to write a script. I am wondering how to declare an array in awk.

I have read the gnu awk manual and found nothing about declare.

i want to test if index ind is in awk array arr.

echo 'awk' | awk 'BEGIN {arr} {if ('1' in arr) arr[ind] = 1}'

i do not declare arr as an array previously and run this in awk gives me such an error.

awk: cmd. line:1: (FILENAME=- FNR=1) fatal: attempt to use scalar `arr' as an array
like image 847
andy Avatar asked Jul 31 '26 00:07

andy


2 Answers

You can use the delete statement to declare an empty array:

BEGIN { delete arr[0] }
END { 
    print "len", length(arr)
    if ("1" in arr) {
        print "astonishing"
    }
}
like image 167
FrankL Avatar answered Aug 01 '26 19:08

FrankL


Your initial arr in the BEGIN block "declares" it to be a scalar. That's what is confusing awk. Just remove that.

like image 42
Etan Reisner Avatar answered Aug 01 '26 18:08

Etan Reisner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!