Operating System - HP-UX
1829883 Members
11764 Online
109993 Solutions
New Discussion

Re: How to sort by two keys?

 
Rashid Ali
Frequent Advisor

How to sort by two keys?

I have a list of ip address as shown below, I want to sort by the last two fields(third one will be the primary key and last field the secondary key). It seems "sort -t. -k3n -k4n file1 " can't work. How should I issue sort command?

Thanks for advices.

128.188.1.102
128.188.1.103
128.188.1.105
128.188.1.52
128.188.1.66
128.188.1.67
128.188.1.68
128.188.1.71
128.188.3.104
128.188.3.15
128.188.3.20
128.188.3.56
128.188.3.58
128.188.3.62
128.188.3.71
128.188.3.88
128.188.3.92
128.188.5.150
128.188.5.162
128.188.5.163
5 REPLIES 5
Carsten Krege
Honored Contributor

Re: How to sort by two keys?

I think your syntax should be correct. However, an easy way to solve this would be:

sort -t. -k3n file1 | sort -t. -k4n

Carsten
-------------------------------------------------------------------------------------------------
In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move. -- HhGttG
Barry O Flanagan
Respected Contributor

Re: How to sort by two keys?

You were very close! The following seems to work for me with the IP list you gave:

sort -t. -k3n,3 -k4n,4

Hope that helps.
Andreas Voss
Honored Contributor

Re: How to sort by two keys?

Hi,

when using the -k option for a specific field you have to define an end_field, otherwise it uses end of line. If you ommit the end_field in the sortkey for field 3 it includes field 4 and the next option for field 4 will be ignored

So this should work:

sort -t. -k3n,3n -k4n file1

Regards
Rashid Ali
Frequent Advisor

Re: How to sort by two keys?

Thank you so much. It did work for me. But I am still wondering why the syntax is so ambiguous, how come "sort -k3,3n -k4,4n" also can work, and "sort -k3n,3n -k4,4n" also can? But "sort -k3,3 -k4,4" cannot?

Another alternative "sort -t. -k3n jp1|sort -t. -k4n" definitely cannot because it is equivalent of one simple sort "sort -t. -k4n".
Barry O Flanagan
Respected Contributor

Re: How to sort by two keys?

Well as far as I know if you put in the n in either the -k3n,3 field or -k4n,4 then it will a numeric sort ie: sort on the numeric values rather than sort by the characters displayed (ASCII values?). The n in both sort keys allows both keys to be sorted numerically. If you specify -n on its own before the first -k then you can leave out the n in both sort keys.

Hope that helps, if all else fails then man sort!