LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   sort by multiple columns (https://www.linuxquestions.org/questions/linux-newbie-8/sort-by-multiple-columns-762774/)

wakatana 10-18-2009 09:48 AM

sort by multiple columns
 
hi all I have file:

154 alfonz novak
154 michael cores
62 jan nedorost
62 martin adrov

and I want to sort by first column numericaly and then by third column alphabeticaly. so output should be:

62 martin adrov
62 jan nedorost
154 michael cores
154 alfonz novak

I tried
Code:

sort -k1n,3 sort
but it gives me:

62 jan nedorost
62 martin adrov
154 alfonz novak
154 michael cores

what I am doing wrong ? Thanks

H_TeXMeX_H 10-18-2009 10:03 AM

Note: This way to do it is wrong, see below.

Code:

bash-3.1$ echo '
154 alfonz novak
154 michael cores
62 jan nedorost
62 martin adrov
' | sort -k1r
62 martin adrov
62 jan nedorost
154 michael cores
154 alfonz novak

so just:

Code:

sort -k1r sort

Telemachos 10-18-2009 10:13 AM

I think this will cover what you're asking for:

Code:

sort -k1,1r -k3 names
(Edited: first shot no good.)

Telemachos 10-18-2009 10:25 AM

Quote:

Originally Posted by H_TeXMeX_H (Post 3723815)
Code:

bash-3.1$ echo '
154 alfonz novak
154 michael cores
62 jan nedorost
62 martin adrov
' | sort -k1r
62 martin adrov
62 jan nedorost
154 michael cores
154 alfonz novak

so just:

Code:

sort -k1r sort

Unless I'm confused, this only reverses the numeric sort on the first field. By coincidence that works on his four names, but what if we add others:

Code:

telemachus ~ $ cat names
154 alfonz novak
62 ashley barone
154 michael cores
62 jan nedorost
154 albert neumann
62 martin adrov

telemachus ~ $ sort -k1r names
62 martin adrov
62 jan nedorost
62 ashley barone
154 michael cores
154 alfonz novak
154 albert neumann

You need to add a second -k flag to deal with his second request (namely sort alphabetically by last name after sorting numberically by first field).

H_TeXMeX_H 10-18-2009 10:40 AM

Oh, yeah, oops. You're right, there should be another one, my bad.

wakatana 10-18-2009 03:35 PM

Thanks guys, I did not know I can put another -k options. so my code looks like
Code:

sort -k1n -k3 names
62 martin adrov
62 jan nedorost
154 michael cores
154 alfonz novak

I tried that with one -k options and comma separate columns (according to man page that way I understood syntax).

Just for curiosity what is difference between "-k1n,3" and "-k1n -k3" teoreticaly both should do the same thing but practice is different


All times are GMT -5. The time now is 08:07 PM.