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?
Best Answer
sort
expects whitespace separated fields. To get it to sort on the port, you should change the field separator: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: