sort -k: Sort by Field or Column
sort -k picks which field to sort on, so you can order a table by its second or third column.
Tool output is usually columnar. -k tells sort which column to key on, and -t says what separates the columns.
What it does
sort -k F1,F2 sorts using the fields from position F1 to F2. With no -t, fields are runs of non-blank separated by blanks (and the leading blank is part of the field). -k2 means "from field 2 to end of line"; -k2,2 means "field 2 only", which is usually what you want.
Common usage
sort -k2 data.txt # from field 2 to end of line
sort -k2,2 data.txt # field 2 only
sort -t: -k3,3n /etc/passwd # numeric sort on the 3rd colon field
sort -k1,1 -k2,2n data.txt # field 1 then numeric field 2Options
| Flag | What it does |
|---|---|
| -k F1,F2 | Sort using fields F1 through F2 |
| -t <char> | Field separator (default: transition from non-blank to blank) |
| -n / -r | Per-key modifiers can attach, e.g. -k3,3n |
| -b | Ignore leading blanks in keys |
| -s | Stable: keep input order for equal keys |
In CI
Always bound the key with -k2,2 rather than -k2; an unbounded key extends to end of line and silently pulls later columns into the comparison. Attach the numeric flag to the key (-k3,3n), not globally, so only that field sorts numerically.
Common errors in CI
With the default separator, a leading space makes the first field appear empty and shifts your column numbers; add -b or set -t explicitly. Mixing GNU and BSD: macOS sort accepts -k but its default whitespace handling differs subtly, so set -t to a literal character for portable scripts.