This is an example of the text file:

How can I sort the lines of the file by second column's last 2 digits? The second column is always five digits.


2 Answers 2


Assuming that the second :-delimited field always contains five digits:

$ sort -t ':' -k2.4,2n file

The -k2.4,2n instructs sort to use the second field, from character 4 onwards (that's what .4 does) to the end of the field as the sorting key, and to sort the input numerically on that key (the n at the end). To sort numerically on the whole second field, you would have used -k2,2n. We use -t ':' to say that fields are delimited by colons.

You can see that it's using the right numbers for sorting if you run the command with --debug (showing both GNU sort and sort on OpenBSD here):

$ gsort --debug -t ':' -k2.4,2n file
gsort: text ordering performed using simple byte comparison
$ sort --debug -t ':' -k2.4,2n file
Memory to be used for sorting: 2139060224
; k1=<23>, k2=<29>; s1=<>, s2=<>; cmp1=-1

Use sort -t: -nk2.4

-t uses the delimiter :
-n for numerical sort
-k your key is the second column

The key definitions are very well explained in info sort.

‘-k POS1[,POS2]’


Specify a sort field that consists of the part of the line between POS1 and POS2 (or the end of the line, if POS2 is omitted), inclusive.

Each POS has the form ‘F[.C][OPTS]’, where F is the number of the field to use, and C is the number of the first character from the beginning of the field. Fields and character positions are numbered starting with 1; a character position of zero in POS2 indicates the field’s last character. If ‘.C’ is omitted from POS1, it defaults to 1 (the beginning of the field); if omitted from POS2, it defaults to 0 (the end of the field). OPTS are ordering options, allowing individual keys to be sorted according to different rules; see below for details. Keys can span multiple fields.

Example: To sort on the second field, use ‘--key=2,2’ (‘-k 2,2’). See below for more notes on keys and more examples. See also the ‘--debug’ option to help determine the part of the line being used in the sort.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .