Re: gawk asort function (207 Views)
Occasional Contributor
Posts: 6
Registered: ‎08-25-2008
Message 1 of 3 (207 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,

Acclaimed Contributor
Posts: 26,108
Registered: ‎03-06-2006
Message 2 of 3 (207 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
Highlighted
Acclaimed Contributor
Posts: 21,184
Registered: ‎07-06-2000
Message 3 of 3 (207 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

# 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 :-}}