# unexpected sort behaviour

Hi

Why is sort doing this:

e\$ sort -k1 -nk2 <<END
X  1
X  3
Y  2
X  4
END

X  1
Y  2
X  3
X  4

I wanted to sort by the first column and then by the second column to get

X 1
X 3
X 4
Y 2

Can i do this in one sort command or do i have to pipe one sort into another

thanks
###### Who is Participating?

Commented:
\$ sort -t" " -k1,1 -k2,2n <<END
> X 12345
> X 567
> X 213
> Y 34
> Y 26
> X 45
> Y 3
> X 12
> END
X 12
X 45
X 213
X 567
X 12345
Y 3
Y 26
Y 34
0

Commented:
sort -k1,2 <END
X  1
X  3
Y  2
X  4
END
0

Commented:
did you try

sort -k1,k2 <<END
X  1
X  3
Y  2
X  4
END
0

Commented:
sort -t" " -k1,1 -nk2,2 <<END
0

Commented:
Woo, typo
sort -k1,2 <<END
X  1
X  3
Y  2
X  4
END
0

Commented:
sorry, correction

sort -k 1,2 <<END
X  1
X  3
Y  2
X  4
END
0

Author Commented:
why dont i need 2 -k flags if i am sorting on 2 fields
0

Author Commented:
i obviously don't understand the comma notation
0

Author Commented:
also why don't i need to use an 'n' to tell sort to sort the second column numerically
0

Commented:
Does it work for you? Try it and let us know.
0

Commented:
The man page show the format of -k option:

http://linux.die.net/man/1/sort

Why you don't need -n , I think it sorts numerically by default
0

Commented:
You need two -k in this case because you want to sort differently on two different columns i.e. first column is tgo be sorted alphabetically and second numerically. Comma notation is

-k, --key=POS1[,POS2]
start a key at POS1 (origin 1), end it at POS2 (default end of line)

If you were to sort both fields alphabetically, you don't need the comma as by default the field definition would extend from the first field to end of the line.
0

Author Commented:
that doesnt work:

andrea@oscar:~/cattle\$ sort -k1.4,2 <<END
X  1123123123
X  3
Y  2
X  4
END

X  1123123123
X  3
X  4
Y  2

0

Author Commented:
andrea@oscar:~/cattle\$ sort -k1,2 <<END
X  1123123123
X  3
Y  2
X  4
END

X  1123123123
X  3
X  4
Y  2
0

Commented:
what is the . (dot) in your command?
0

Commented:
sort -k1,1 -nk2,2 <<END
X  12345
X  3
X  4
Y  2
END
0

Author Commented:
thank you. i had misunderstood the comma notation
0

Author Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.