4

I have this output I'd like to sort numerically by port (starting at the 35th column):

tcp        0      0 192.168.0.210:110       0.0.0.0:*  LISTEN  3385/dovecot
tcp        0      0 192.168.0.210:143       0.0.0.0:*  LISTEN  3385/dovecot
tcp        0      0 192.168.0.210:22        0.0.0.0:*  LISTEN  2223/sshd
tcp        0      0 192.168.0.210:25        0.0.0.0:*  LISTEN  3589/master
tcp        0      0 192.168.0.210:443       0.0.0.0:*  LISTEN  2037/apache
tcp        0      0 192.168.0.210:587       0.0.0.0:*  LISTEN  3589/master
tcp        0      0 192.168.0.210:80        0.0.0.0:*  LISTEN  2037/apache
#                                 ^
#                                 Sorted at this column (#35)

So that the new output looks like this (lowest port first):

tcp        0      0 192.168.0.210:22        0.0.0.0:*  LISTEN  2223/sshd
tcp        0      0 192.168.0.210:25        0.0.0.0:*  LISTEN  3589/master
tcp        0      0 192.168.0.210:80        0.0.0.0:*  LISTEN  2037/apache
tcp        0      0 192.168.0.210:110       0.0.0.0:*  LISTEN  3385/dovecot
tcp        0      0 192.168.0.210:143       0.0.0.0:*  LISTEN  3385/dovecot
tcp        0      0 192.168.0.210:443       0.0.0.0:*  LISTEN  2037/apache
tcp        0      0 192.168.0.210:587       0.0.0.0:*  LISTEN  3589/master
#                                 ^
#                                 Sorted at this column (#35)

I've played around with all different forms of |sort, including:

|sort -n         # <- I thought this would work
|sort -nk35
|sort -nk35,37

Etcetera, etcetera. Maybe I'm misunderstanding the purpose of the -k flag? Or maybe those colons are messing things up?

1 Answer 1

4

sort expects whitespace separated fields. To get it to sort on the port, you should change the field separator:

sort -t: -nk2 file

Here, I am telling sort to take : as the field separator. Therefore the first characters of the second field are the port number and it sorts as you want it to:

$ sort -t: -nk2 file
tcp        0      0 192.168.0.210:22        0.0.0.0:*  LISTEN  2223/sshd
tcp        0      0 192.168.0.210:25        0.0.0.0:*  LISTEN  3589/master
tcp        0      0 192.168.0.210:80        0.0.0.0:*  LISTEN  2037/apache
tcp        0      0 192.168.0.210:110       0.0.0.0:*  LISTEN  3385/dovecot
tcp        0      0 192.168.0.210:143       0.0.0.0:*  LISTEN  3385/dovecot
tcp        0      0 192.168.0.210:443       0.0.0.0:*  LISTEN  2037/apache
tcp        0      0 192.168.0.210:587       0.0.0.0:*  LISTEN  3589/master
2
  • 1
    Aaahh! I thought -k was the overall column. Great, thanks!
    – Jeff
    Sep 5, 2013 at 13:52
  • @Jeff -k is the column, however the columns are defined by the field separator.
    – terdon
    Sep 5, 2013 at 13:59

You must log in to answer this question.

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