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
andiejeAsked:
Who is Participating?
 
amit_gConnect With a Mentor 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
 
wesly_chenCommented:
sort -k1,2 <END
X  1
X  3
Y  2
X  4
END
0
 
omarfaridCommented:
did you try

sort -k1,k2 <<END
X  1
X  3
Y  2
X  4
END
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
amit_gCommented:
sort -t" " -k1,1 -nk2,2 <<END
0
 
wesly_chenCommented:
Woo, typo
sort -k1,2 <<END
X  1
X  3
Y  2
X  4
END
0
 
omarfaridCommented:
sorry, correction

sort -k 1,2 <<END
X  1
X  3
Y  2
X  4
END
0
 
andiejeAuthor Commented:
why dont i need 2 -k flags if i am sorting on 2 fields
0
 
andiejeAuthor Commented:
i obviously don't understand the comma notation
0
 
andiejeAuthor Commented:
also why don't i need to use an 'n' to tell sort to sort the second column numerically
0
 
amit_gCommented:
Does it work for you? Try it and let us know.
0
 
omarfaridCommented:
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
 
amit_gCommented:
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
 
andiejeAuthor 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
 
andiejeAuthor 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
 
omarfaridCommented:
what is the . (dot) in your command?
0
 
wesly_chenConnect With a Mentor Commented:
sort -k1,1 -nk2,2 <<END
X  12345
X  3
X  4
Y  2
END
0
 
andiejeAuthor Commented:
thank you. i had misunderstood the comma notation
0
 
andiejeAuthor 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.

All Courses

From novice to tech pro — start learning today.