Rish
Rish

Reputation: 826

awk array that contains 0 prints as empty space

To illustrate my issue, here is a simple example:

cat file1.txt

user1
user2
user3
user4

cat file2.txt

user1 0
user2 3
user3 8
user6 9

awk 'NR==FNR { a[$1]=$2; next } { print $1, a[$1] ? a[$1] : "NA" }' file2.txt file1.txt

user1 NA
user2 3
user3 8
user4 NA

I need the 0 to be printed after user1, but it's printing NA as if user1 did not exit in file2.txt

I'm sure there is a simple solution, but why is this the case?

PS. I am aware that of the grep -f solution here, but I'm just wondering what I'm doing wrong in the array.

Upvotes: 2

Views: 77

Answers (1)

Mark Reed
Mark Reed

Reputation: 95297

When evaluating an expression as a Boolean condition, AWK considers a string whose numeric value is zero to be false, so you will always get "NA" for the users whose associated number is 0. (The same is true of the empty string, which would appear in the array if a user were listed in file2.txt with no number after their name at all.)

To reliably print all the numbers from file2.txt, you need to change the test condition from one that depends on the value of a[$1] to one that simply checks for the presence of the key $1 in the array. This should work:

print $1, ($1 in a ? a[$1] : "NA")

That will only print "NA" if the key is missing from the array entirely.

Upvotes: 7

Related Questions