Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

unix sort

Status
Not open for further replies.

warmongr

MIS
Mar 17, 1999
214
US
Just curious if anyone has seen this before. Not really a server related question but I'm a member of this forum and you guys are pretty smart so here goes.

Let's say I have a file:

Goatboy,4
Harwood,12
Pacman,22
CandyAndy,10
Chadwick,55
Goatboy,10
SeaMonkey,2
Buttprimer,15
Cancer,12

and I want to sort first alph on field 1 and second numerically on field 2. I use the sort syntax

sort -t, -k1 -k2n sortfilenamehere

The desire would be something like this.

Buttprimer,15
Cancer,12
CandyAndy,10
Chadwick,55
<b>Goatboy,4</b>
<b>Goatboy,10</b>
Harwood,12
Pacman,22
SeaMonkey,2

but what I actually am getting is

...
Goatboy,10
Goatboy,4
...

If I just sort on field 2 numerically sort understands that 4 comes before 10...

sort -t, -k2n sortfilenamehere

Anyone have any advice here? I'm using bash on a FC 6 and I've also tried on a RHEL4 box.

Warmongr
 
How about:
[tt]
sed 's/,\(.\)$/,0\1/' filename | sort | sed 's/,0/,/'
[/tt]
 
Try this...
Code:
sort -t, -k 1,1 -k 2,2n sortfilenamehere
 
TonyGroves you lost me. I'll try it but not sure I understand what this means.
 
Hey SamBones,

Thanks,

I must have tried every other combination. Good to have a second set of eyes.

War
 
There's no need to try my solution; Sam Bones's is much better. But if you want to know how it works, here goes.

1. sed adds a leading zero to every single-character second field value, so that we get:[tt]
...
Goatboy,04
...
Goatboy,10
...[/tt]
2. Then the resulting list is sorted alphanumerically.
3. Then the leading zeroes are stripped from the second field in the sorted list, giving:[tt]
...
Goatboy,4
Goatboy,10
...[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top