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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
Assuming that the second
:-delimited field always contains five digits:
$ sort -t ':' -k2.4,2n file 22.214.171.124:21023:400 126.96.36.199:21029:400
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 on OpenBSD here):
$ gsort --debug -t ':' -k2.4,2n file gsort: text ordering performed using simple byte comparison 188.8.131.52:21023:400 __ _______________________ 184.108.40.206:21029:400 __ _______________________
$ sort --debug -t ':' -k2.4,2n file Memory to be used for sorting: 2139060224 sort_method=heapsort ; k1=<23>, k2=<29>; s1=<220.127.116.11:21023:400>, s2=<18.104.22.168:21029:400>; cmp1=-1 22.214.171.124:21023:400 126.96.36.199:21029:400
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
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.