For Programmers: Free Programming Magazines  


Home > Archive > AWK > December 2004 > Numerical order









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Numerical order
jaf893@gmail.com

2004-12-07, 3:59 am

I have a list in the following format

text number
text number
text number

How can I sort this list into numerical order using the numbers in the
2nd column?

William James

2004-12-07, 3:59 am

BEGIN \
{
split( "a 1111!bb 222!ccc 33!dddd,4", array, /!/ )
sort( array, 1, "[^ ,]*$" )
for (i=1;i in array;i++)
print array[i]

print ""
split( "bar aaaa!foo aaa!moose aa!goose a~", array, /!/ )
sort( array, 0, " +", "[^a-z]" )
for (i=1;i in array;i++)
print array[i]
}

## If 1 regexp. is given, sort on what matches it.
## If 2 are given, sort on what lies between.
function sort( a, num, re1, re2 ,i,j,k,s1,s2,temp )
{ for (i=2; i in a; i++)
{ s1 = sort_on( a[i], re1, re2 )
for (j=1; j<i; j++)
{ s2 = sort_on( a[j], re1, re2 )
if (num)
{ if (s1+0 < s2+0) break
}
else
if (s1 < s2) break
}
temp = a[i]
for (k=i; k>j; k--)
a[k] = a[k-1]
a[k] = temp
}
}

function sort_on( s, r1, r2 )
{ if (!r1)
return s
match( s, r1 )
{ if (r2)
{ s = substr( s, RSTART + RLENGTH )
if ( match( s, r2 ) )
return substr( s, 1, RSTART - 1)
return s
}
else
return substr( s, RSTART, RLENGTH )
}
}
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com