I want to print IP address and hostname from /etc/hosts using a shell script

/etc/hosts file :

## #For example:
## #     rhino.acme.com          # source server
## #      x.acme.com              # x client host
## #localhost name resolution is handled within DNS itself.
##  #       localhost
##  #::1             localhost  aaaa.aa.aa  aaaa.aa.aa  aaaa.aa.aa  aaaa.aa.aa

# #     bbb.bb.bb
# #     ccc.cc.cc

I need output valid IP address and host name not all lines  aaaa.aa.aa  aaaa.aa.aa  aaaa.aa.aa  aaaa.aa.aa

not all the lines

  • Which IP address and which hostname? Can you be more specific on what you are trying to achieve? What have you tried? What results did you expect and what results did you get instead? What kind of errors? – filbranden May 4 '18 at 5:40
  • Hi Filipe, i have list of ipaddress and their hostnames are maintains in /etc/host. Im trying to print (only) ipaddress and hostname from the hosts file. – Kannan M May 4 '18 at 5:47
  • 2
    @KannanM The /etc/hosts file is usually in localhost format, IP on left and hostname on right. To print that you just need cat /etc/hosts. This is what we understand, so if this is not what you want - please edit your question and include example of how you want it to look like – Sergiy Kolodyazhnyy May 4 '18 at 5:50
  • 3
    If you want to filter for IPv4 addresses only and get rid of comments and IPv6 stuff, try grep -E "^([[:digit:]]+\.){3}[[:digit:]]+" /etc/hosts – Philippos May 4 '18 at 6:01
  • 2
    Personally, I'd say it's sufficient to just do grep -v '#', since the format for the /etc/hosts file, at least according to the manual, is only IP_address canonical_hostname optional_aliasies. The only other thing that seems to be alright there is comments, which start with #. But that's just my view. – Sergiy Kolodyazhnyy May 4 '18 at 6:19

Try this

sed -e '/^#/d' -e '/^\s*$/d' /etc/hosts

will delete all lines starts with # and blank lines.

  • It will, however, not deal with comments that does not start at the start of the line, which is a supported type of comment in the /etc/hosts file. – Kusalananda May 9 '18 at 12:22

Removing commented out and empty lines form /etc/hosts:

sed -e 's/#.*//' -e 's/[[:blank:]]*$//' -e '/^$/d' /etc/hosts

This uses three sed expressions in the following order:

  1. Remove everything after a # (including the #).
  2. Remove blanks (spaces or tabs) at the end of lines.
  3. Delete empty lines.

Given your example file, this produces  aaaa.aa.aa  aaaa.aa.aa  aaaa.aa.aa  aaaa.aa.aa

This obviously does not try to validate the addresses and names that are left.


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.