LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   printing array in awk (http://www.linuxquestions.org/questions/linux-newbie-8/printing-array-in-awk-846260/)

ghantauke 11-24-2010 08:10 AM

printing array in awk
 
is there anyway i can print out all elements of an array in awk without knowing what the indices are? or even indices and elements pairs for that matter. i thought about using a for loop but without knowing what the indices are i don't know how to do it.

colucix 11-24-2010 08:14 AM

If the indices are numeric and sorted
Code:

for (i = 1; i <= length(array); i++)
    print i, array[i]

Actually the length function was implemented to return the length of a string. Since gawk version 3.1.5, if the argument is an array, it returns the number of elements stored in the array.

If the indices are made of unsorted alphanumeric strings you can simply do
Code:

for (i in array)
    print i, array[i]


ghantauke 11-24-2010 08:20 AM

nevermind guess you edited your post ^^

PTrenholme 11-24-2010 09:16 AM

For what it's worth, even if you have a multi-dimensional array a simple change to colucix's suggestion could be used:
Code:

for (index in array) {
    readable_index=gensub(SUBSEP,", ","G",index)
    print "array["readable_index"] = " array[index]
}

You might want to look at the asort and asorti functions if the order of the array elements is of significance.

Note: Some of the above is specific to gawk, and may not be portable.


All times are GMT -5. The time now is 02:57 AM.