Karn Kumar Karn Kumar - 6 months ago 24
Python Question

getent hosts to take initial 3 up digit+hostname unix

I need first 3 octets of IP address and the myhosts name, while I am trying to make via cut command but unable to join the host name

$ getent hosts myhosts myhosts.lab.com

anything with awk, sed, cut, python will be okay

$ getent hosts myhosts | cut -d "." -f1,2,3

The output should be:

172.10.2 myhosts.lab.com


On the first field, remove everything from the last dot:

$ awk '{sub(/\.[^.]*$/,"",$1); print $1, $2}' <<< "    myhosts.lab.com"
172.10.2 myhosts.lab.com

We have two fields: IP and hostname. The hostname is to be returned without any change, whereas for the IP we want to remove the last block.

To tune the first field $1 we use sub(). This perform replacements using the syntax sub(regexp, replacement [, target]). To remove everything from the last dot, we replace it with the empty string.

And how do we match everything from the last dot? Using /\.[^.]*$/, which means: match a dot and then any kind of characters but a dot until the end of the field.