0

This is an example of the text file:

195.92.211.47:21029:400
195.92.211.48:21023:400

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

3

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

$ sort -t ':' -k2.4,2n file
195.92.211.48:21023:400
195.92.211.47:21029:400

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
195.92.211.48:21023:400
                 __
_______________________
195.92.211.47:21029:400
                 __
_______________________
$ sort --debug -t ':' -k2.4,2n file
Memory to be used for sorting: 2139060224
sort_method=heapsort
; k1=<23>, k2=<29>; s1=<195.92.211.48:21023:400>, s2=<195.92.211.47:21029:400>; cmp1=-1
195.92.211.48:21023:400
195.92.211.47:21029:400
2

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]’

‘--key=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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.