I am trying to sort on multiple columns. The results are not as expected.
Here's my data (people.txt):
Simon Strange 62
Pete Brown 37
Mark Brown 46
Stefan Heinz 52
Tony Bedford 50
John Strange 51
Fred Bloggs 22
James Bedford 21
Emily Bedford 18
Ana Villamor 44
Alice Villamor 50
Francis Chepstow 56
The following works correctly:
bash-3.2$ sort -k2 -k3 <people.txt
Emily Bedford 18
James Bedford 21
Tony Bedford 50
Fred Bloggs 22
Pete Brown 37
Mark Brown 46
Francis Chepstow 56
Stefan Heinz 52
John Strange 51
Simon Strange 62
Ana Villamor 44
Alice Villamor 50
But, the following does not work as expected:
bash-3.2$ sort -k2 -k1 <people.txt
Emily Bedford 18
James Bedford 21
Tony Bedford 50
Fred Bloggs 22
Pete Brown 37
Mark Brown 46
Francis Chepstow 56
Stefan Heinz 52
John Strange 51
Simon Strange 62
Ana Villamor 44
Alice Villamor 50
I was trying to sort by surname and then by first name, but you will see the Villamors are not in the correct order. I was hoping to sort by surname, and then when surnames matched, to sort by first name.
It seems there is something about how this should work I don't understand. I could do this another way of course (using awk), but I want to understand sort.
I am using the standard Bash shell on Mac OS X.
sort
can operate onfile
directly no ? Likesort -n ... file
– han solo Nov 11 '19 at 13:48stdin
ofsort
for no reason in the post. That's why :) Also great answer, i wasn't sure how to limit the column for comparison – han solo Nov 12 '19 at 05:03