Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing blank lines when looping associative array in AWK

Tags:

awk

I am not clear why blank lines are being printed instead of their correct values from day[] array in AWK.

BEGIN{
        day[1]="Sunday"
        day["first"]="Sunday"
        day[2]="Monday"
        day["second"]="Monday"
        day[4]="Wednesday"
        day["fourth"]="Wednesday"
        day[3]="Tuesday"
        day["third"]="Tuesday"
        for (i in day)
        {
            print $i
            print day[$i]
        }
}

Explicity printing out individual array elements yield the expected values as follows:

 BEGIN{
        day[1]="Sunday"
        day["first"]="Sunday"
        day[2]="Monday"
        day["second"]="Monday"
        day[4]="Wednesday"
        day["fourth"]="Wednesday"
        day[3]="Tuesday"
        day["third"]="Tuesday"
        print day[1]
        print day["first"]
        print day[2]
        print day["second"]
        print day[3]
        print day["third"]
        print day[4]
        print day["fourth"]
}

I am running Linux fedora 5.12.11-300.

Many thanks in advance,

Mary

like image 698
George Jackson Avatar asked Dec 07 '25 07:12

George Jackson


1 Answers

You shouldn't use $ while printing i or array value as it refers to value of field in awk language, use following instead. Also you need not to use 2 times print statements, you could use single print with newline in it too.

awk '
BEGIN{
        day[1]="Sunday"
        day["first"]="Sunday"
        day[2]="Monday"
        day["second"]="Monday"
        day[4]="Wednesday"
        day["fourth"]="Wednesday"
        day[3]="Tuesday"
        day["third"]="Tuesday"
        for (i in day)
        {
           print i ORS day[i]
        }
}'

Improved version of awk: Also you need to to use 2 statements for same value, you can define them in single assignment way. Even with different indexes having same values it should work, that will save few lines of code :)

awk '
BEGIN{
        day[1]=day["first"]="Sunday"
        day[2]=day["second"]="Monday"
        day[4]=day["fourth"]="Wednesday"
        day[3]=day["third"]="Tuesday"
        for (i in day)
        {
            print i OFS day[i]
        }
}'
like image 188
RavinderSingh13 Avatar answered Dec 09 '25 06:12

RavinderSingh13