5

I am brand new to AWK and trying to determine if my array is empty or not so i can print a message if so. Typically i am use to length functions and can check like that, but it does not seem AWK has those. Here is my working code, i just want to print out a different message if there is nothing in the array after parsing all my data.

#add to array if condition is met
if ($2 == "SOURCE" && $4 == "RESTRICTED"){
    sourceAndRestricted[$3]++;
}
#print out array
for (var in sourceAndRestricted){
    printf "\t\t"var"\n" 
}

ive tried something like this and its not working. Suggestions?

for (var in sourceAndRestricted){
    if (var > 1){
        printf "\t\t"var"\n" 
    }
    else {
        print "NONE"
    }
}
1
  • Keep a counter in the for loop and check it after? Commented Nov 19, 2013 at 15:48

2 Answers 2

11

Check it with length() function:

if ( length(sourceAndRestricted) > 0 ) {
    printf "\t\t"var"\n"
}
else
    print "NONE"
}
Sign up to request clarification or add additional context in comments.

6 Comments

gawk 3.1.5 and newer only. I don't know about other awk:s.
@EtanReisner: It works for me with --traditional switch too, that teorically make it works without GNU extensions.
did not know there was a length function! Thank you very much, this worked!
length(array) is considered an extension in gawk and I hear it works in OSX awk too but it's definitely not portable.
There is a downside to this: gawk 'BEGIN{if(length(arr)==0) arr[1]=1}' produces an error: gawk: cmd. line:1: fatal: attempt to use scalar 'arr' as an array.
|
11
$ cat tst.awk
function isEmpty(arr, idx) {for (idx in arr) return 0; return 1}

BEGIN {
   map[3] = 27

   print isEmpty(map)

   delete map[3]

   print isEmpty(map)
}
$ awk -f tst.awk
0
1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.