Computing.Net > Forums > Unix > Sort Order Presevation

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Sort Order Presevation

Reply to Message Icon

Name: Graeme Conn
Date: September 2, 2005 at 07:16:34 Pacific
OS: unix
CPU/Ram: B.11.11 U 9000/800
Comment:

Take the simple input file:

5BBBBBBBBBBBBBBB1
5BBBBBBBBBBBBBBB2
2BBBBBBBBBBBBBBB1
2BBBBBBBBBBBBBBB3
2BBBBBBBBBBBBBBB2

I need to sort this on position 2-16 and postions 1-1 which is a record type. However I need to preserve the sort order, when I apply the following sort -k 1.2,1.15 -k 1.1,1.1 on this file, I end up with :

2BBBBBBBBBBBBBBB1
2BBBBBBBBBBBBBBB2
2BBBBBBBBBBBBBBB3
5BBBBBBBBBBBBBBB1
5BBBBBBBBBBBBBBB2

I want:
2BBBBBBBBBBBBBBB1
2BBBBBBBBBBBBBBB3
2BBBBBBBBBBBBBBB2
5BBBBBBBBBBBBBBB1
5BBBBBBBBBBBBBBB2

Help !




Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: September 2, 2005 at 08:58:44 Pacific
Reply:

Obviously, sort doesn't guarantee the order of any columns or fields not sorted on. One trick is to add a dummy column to your file, perform a secondary sort, and, finally, remove the column:

cat -n myfile|sort -k 2.2,1.15 -k 2.1,1.1 -k 1|awk ' { print $2 } '

The above command should deliver the desired output.

See a further discussion here:

http://www.unixreview.com/documents/s=9811/ur0506h/ur0506h.html


0

Response Number 2
Name: Graeme Conn
Date: September 2, 2005 at 09:14:41 Pacific
Reply:

thanks, exactlty what I was thinking. I was hoping the unix sort would be clever enough. This was not an issue on the old ibm mainframe sort utility....mmmmmm.


0

Response Number 3
Name: Luke Chi
Date: September 6, 2005 at 14:52:12 Pacific
Reply:

It's stupid, but it's true that sort "guarantees" the order of any columns or fields not sorted on. We just can't disable it.

If you specify -r which is descending order, the order of any columns or fields not sorted on will be in decending order.

If you DON'T specify -r, the order of any columns or fields not sorted on will be in ascending order.

Luke Chi


0

Response Number 4
Name: Luke Chi
Date: September 6, 2005 at 15:22:19 Pacific
Reply:

cat -n k | sort -k 1.9,1.22 -k 1.8,1.8 -k 1|awk ' { print $2 }'

Luke Chi


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


Awk withing an awk? replace a column with a n...



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: Sort Order Presevation

Sorting in C www.computing.net/answers/unix/sorting-in-c/5628.html

Numerical sort with sort www.computing.net/answers/unix/numerical-sort-with-sort/7380.html

Help with comparisons www.computing.net/answers/unix/help-with-comparisons/4838.html