![]() |
|
|
grep unix.com with google
|
|||||||
| Forums | Register | Blog | Man Pages | Forum Rules | Links | Albums | FAQ | Our Members | Calendar | Search | Today's Posts | Mark Forums Read |
| UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !! |
![]() |
|
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|||
|
Sort file using 2 columns
Hi, I am trying to sort a file first by the string column, then by the number column. file: Code:
xyz1 2 xyzX 4 xyz2 1 xyz13 3 xyz11 5 xyz13 10 xyz1 1 xyz10 1 xyz4 2 result should be Code:
xyz1 1 xyz1 2 xyz2 1 xyz4 2 xyz10 1 xyz11 5 xyz13 3 xyz13 10 xyzX 4 I have tried many sort commands and failed. Please help! ---------- Post updated at 02:45 PM ---------- Previous update was at 12:32 AM ---------- please help! Last edited by fargo; 11-28-2009 at 03:44 PM.. |
|
|||
|
You have to specify a numerical sort for the second column otherwise it will get sorted alphabetically. This should do it: Code:
sort -k1,1 -k2,2n infile With my sort you have to use a comma in the key field specification or it does not work right. Also, if you use -t' ' it seems to use single space separation instead of multispace separation and also produce incorrect result. Without -t it produces: Code:
xyz1 1 xyz1 2 xyz10 1 xyz11 5 xyz13 3 xyz13 10 xyz2 1 xyz4 2 xyzX 4 But you required a numerical sort on the second part of the first key. For that the first key needs to be split into an alphabetical part and a numerical part during the sort phase. A numerical sort places X at the top though, not at the bottom. Code:
sed 's/\(...\)/\1 /' infile|sort -k1,1 -k2,2n -k3,3n|sed 's/ //' produces: Code:
xyzX 4 xyz1 1 xyz1 2 xyz2 1 xyz4 2 xyz10 1 xyz11 5 xyz13 3 xyz13 10 Last edited by Scrutinizer; 11-29-2009 at 04:47 AM.. |
| Sponsored Links | ||
|
|
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Sort on multi columns | gio001 | UNIX for Dummies Questions & Answers | 2 | 09-01-2009 06:44 PM |
| sort columns by field | kamel.seg | Shell Programming and Scripting | 4 | 02-20-2008 06:50 AM |
| add columns from file to another and sort | kamel.seg | Shell Programming and Scripting | 12 | 12-12-2007 02:39 PM |
| Help needed to sort multiple columns in one file | ahjiefreak | UNIX for Dummies Questions & Answers | 1 | 12-07-2007 05:50 AM |
| Sort by Columns | murbina | UNIX for Dummies Questions & Answers | 1 | 05-10-2004 03:21 PM |