1752794 Members
5890 Online
108789 Solutions
New Discussion юеВ

Re: gawk asort function

 
OTii
Occasional Contributor

gawk asort function

Hi, I google a bit but couldn't find what I need. Hope some expert can help me.

I have an array stored with numeric data, however when I call the asort(array) function, The sorted array is based on string comparision (1, 10, 11, 2, 20, 3, 4,5 ..). How do I sort in numeric order (1,2,3,4,...), I need to do this in gawk.

thanks,

2 REPLIES 2
Dennis Handly
Acclaimed Contributor

Re: gawk asort function

I have no problems with gawk 3.1.4 and numeric values with asort. Provided the values weren't in quotes to start:
gawk '
BEGIN {
s[10] = 2
s[11] = 1
s[12] = 3
s[13] = 10
asort(s)
print s[1]
print s[2]
print s[3]
print s[4]
for (i in s)
print i, s[i]
exit
}' /dev/null
James R. Ferguson
Acclaimed Contributor

Re: gawk asort function

Hi:

Perl offers the ability to sort in numeric versus alphabetic order merely by switching to the "spaceship" operator from the 'cmp' operator. Consider:

# perl -le '@n=qw(2 1 3 10);print for sort {$a <=> $b} @n'
1
2
3
10

...instead of:

# perl -le '@n=qw(2 1 3 10);print for sort {$a cmp $b} @n'
1
10
2
3

...As you see, Perl would have solved a problem that forced you to move from 'awk' to 'gawk' anyway :-}}

http://forums11.itrc.hp.com/service/forums/questionanswer.do?threadId=1262693

Regards!

...JRF...