Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an associative array in awk

Tags:

I have an associative array in awk that gets populated like this:

chr_count[$3]++ 

When I try to print my chr_counts, I use this:

for (i in chr_count) {     print i,":",chr_count[i]; } 

But not surprisingly, the order of i is not sorted in any way. Is there an easy way to iterate over the sorted keys of chr_count?

like image 431
lonestar21 Avatar asked Mar 16 '10 21:03

lonestar21


2 Answers

Instead of asort, use asorti(source, destination) which sorts the indices into a new array and you won't have to copy the array.

Then you can use the destination array as pointers into the source array.

For your example, you would use it like this:

n=asorti(chr_count, sorted) for (i=1; i<=n; i++) {         print sorted[i] " : " chr_count[sorted[i]] } 
like image 178
Dennis Williamson Avatar answered Feb 14 '23 03:02

Dennis Williamson


you can use the sort command. e.g.

for ( i in data )  print i ":", data[i]  | "sort" 
like image 30
krishna murti Avatar answered Feb 14 '23 04:02

krishna murti