# Sorting Awk generalized array

**URL:** <https://community.unix.com/t/sorting-awk-generalized-array/232495>\
**Category:** Shell Programming and Scripting\
**Created:** [February 20, 2009, 6:45pm UTC](https://community.unix.com/t/sorting-awk-generalized-array/232495 "2009-02-20T18:45:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gio001](https://community.unix.com/letter_avatar/gio001/32/5_5575768a8748004e209b776fc1b2916d.png) [@gio001](https://community.unix.com/u/gio001)\
**Post date:** [February 20, 2009, 6:45pm UTC](https://community.unix.com/t/sorting-awk-generalized-array/232495/1 "2009-02-20T18:45:17Z")

</div>

Generalized arrays take any type of variable(s) as subscripts, but the subscript(s) are treated as one long string expression.  
The use of for(a in x) on a generalized array will return all of the valid subscripts in some order, not necessarily the one you wished.

How can I make it so that i get the items returned sorted ...... ?

---

<div class="post-metadata">

**Author:** ![Shahul](https://community.unix.com/user_avatar/community.unix.com/shahul/32/1043_2.png) [@Shahul](https://community.unix.com/u/Shahul)\
**Post date:** [February 20, 2009, 10:32pm UTC](https://community.unix.com/t/sorting-awk-generalized-array/232495/2 "2009-02-20T22:32:36Z")

</div>

Hi ,

Could you just share your code..or some sample.!!!!!  
..

Thanks  
Sha

---

<div class="post-metadata">

**Author:** ![Franklin52](https://community.unix.com/user_avatar/community.unix.com/franklin52/32/500_2.png) [@Franklin52](https://community.unix.com/u/Franklin52)\
**Post date:** [February 21, 2009, 8:59am UTC](https://community.unix.com/t/sorting-awk-generalized-array/232495/3 "2009-02-21T08:59:22Z")

</div>

The order is somewhat random and may vary among the many implementations of awk.  
This is an example how to to print the array in the order it's created. It uses a helper array b to hold the order of the main array (use nawk or /usr/xpg4/bin/awk on Solaris if you get errors):

```nohighlight
awk '{a[$1]=$0;b[++n]=$1}
END{for(i=1;i<=n;i++)print a[b]}' file

```

With this example it's also possible to access a specific number of an element of the array, for instance, to print the 5th element:

```nohighlight
awk '{a[$1]=$0;b[++n]=$1}
END{print a[b[5]]}' file

```

And this example shows how you can sort an array with the external sort command if you don't have gawk:

```nohighlight
awk '{a[$1]=$0}END{for(i in a)print a|"sort"}' file

```

Regards
