Lessons · Terminal · sort -k: on which column
Sorting on a column
-k N starts the sort key at field N. It runs to the END of the line unless you name a stop, which is what -k2,2 means.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Real data is columns and the interesting one is rarely the first.
How to think about it
-k2 -n for a number in the second column; -k2,2 when a third column should not break ties.
Worked example
sort -k2 people.txtBy the second field, as text: 200, 30, 4.
sort -k2 -n people.txtAs numbers: 4, 30, 200.
sort -k2,2 -n people.txtSame here, and immune to a third column.
Your turn
Sort app.log on its second column.
sort 2 app.log
Try it at a real prompt
The trap
-k2 means from field two onwards. On a line with three columns it is not the same sort as -k2,2, and the difference only shows up on ties.
Practise sort -k: on which column on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.