Print IP Addresses and Hostnames From Host File on Linux

Print IP Addresses and Hostnames From Host File on Linux

The host file, located at /etc/hosts on Linux systems, is a crucial part of the networking configuration. It maps hostnames to IP addresses, allowing the system to resolve domain names locally before querying external DNS servers. Sometimes, it becomes necessary to view the entries in this file for troubleshooting or verification purposes. This tutorial explains how to print IP addresses and hostnames from a host file on Linux.

Run the following grep command along with a regular expression to filter out comments and empty lines, providing a clean and concise output:

grep -vE '^(\s*$|#)' /etc/hosts

Explanation of the command:

  • -v - inverts the matching. Displays lines that do not match the given pattern.
  • -E - enables extended regular expressions for more complex a pattern matching.
  • ^(\s*$|#) - this regular expression matches lines that are either empty or contain only whitespace characters (\s*) or start with a hash symbol (#). This effectively filters out comments and empty lines from the output.

By using this command, we can retrieve a list of IP addresses and corresponding hostnames from the host file, making it easier to review and manage networking configurations on a Linux system.

Output example:    localhost    ubuntu
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Leave a Comment

Cancel reply

Your email address will not be published.