Simpler Navigation for Servers and Operating Systems
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
cancel
Showing results for 
Search instead for 
Did you mean: 

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
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
Highlighted
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...