How do you sort a host table by IP Address on a UNIX network management platform?
This has been a basic requirement, since the dawn of The Internet.
Let's look at an example /etc/hosts extract:
sun9999/user$ cat /etc/hosts
#
127.0.0.1 localhost
::1 localhost
201.14.24.17 BT-Site-1 # LasPalmas
203.16.54.112 QB-Site-1 # NorthSydney
201.14.24.21 DL-Site-1 # LasPalmas
202.135.192.97 QB-Site-1 # NorthSydney
203.16.54.18 PR-Site-1 # NorthSydney
201.14.24.28 DL-Site-2 # LasPalmas
203.16.54.22 KP-Site-1 # NorthSydney
Each octet in an IPv4 address is separated by a period "." and a simple POSIX sort will use the period as the field separator and then request a numeric sort on the first, second, third, and fourth octets.
sun9999/user$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts
::1 localhost
#
127.0.0.1 localhost
201.14.24.17 BT-Site-1 # LasPalmas
201.14.24.21 DL-Site-1 # LasPalmas
201.14.24.28 DL-Site-2 # LasPalmas
202.135.192.97 QB-Site-1 # NorthSydney
203.16.54.18 PR-Site-1 # NorthSydney
203.16.54.22 KP-Site-1 # NorthSydney
203.16.54.112 QB-Site-1 # NorthSydney
What it you want to eliminate colon ":" separated IPv6 addresses, empty lines, and lines with comments? Just perform a little POSIX awk'ing after the sort.
Want to eliminate all localhost entries? Add a localhost elimination pattern:sun9999/user$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts | awk '$1!~/:/ && !/^$/ && !/^#/'127.0.0.1 localhost
201.14.24.17 BT-Site-1 # LasPalmas
201.14.24.21 DL-Site-1 # LasPalmas
201.14.24.28 DL-Site-2 # LasPalmas
202.135.192.97 QB-Site-1 # NorthSydney
203.16.54.18 PR-Site-1 # NorthSydney
203.16.54.22 KP-Site-1 # NorthSydney
203.16.54.112 QB-Site-1 # NorthSydney
Need to print only the host name, sorted by IP Address, for entries managed by NorthSydney NOC?sun9999/user$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts | awk '$1!~/:/ && !/^$/ && !/^#/ && !/localhost/'201.14.24.17 BT-Site-1 # LasPalmas
201.14.24.21 DL-Site-1 # LasPalmas
201.14.24.28 DL-Site-2 # LasPalmas
202.135.192.97 QB-Site-1 # NorthSydney
203.16.54.18 PR-Site-1 # NorthSydney
203.16.54.22 KP-Site-1 # NorthSydney
203.16.54.112 QB-Site-1 # NorthSydney
sun9999/user$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts |
awk '$1!~/:/ && !/^$/ && !/^#/ && !/localhost/ && /NorthSydney/ {
print $2 }'
QB-Site-1
PR-Site-1
KP-Site-1
QB-Site-1
If you are not using POSIX commands to do standard network management work, you don't know what you are missing!
No comments:
Post a Comment