Re: gawk asort function (98 Views)
Reply
Occasional Contributor
OTii
Posts: 6
Registered: ‎08-25-2008
Message 1 of 3 (98 Views)

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,

Please use plain text.
Acclaimed Contributor
Dennis Handly
Posts: 24,742
Registered: ‎03-06-2006
Message 2 of 3 (98 Views)

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
Please use plain text.
Acclaimed Contributor
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 3 of 3 (98 Views)

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


Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation