Fetch ipaddress and hostname from host file.

hello guys,

I have a query ,I am looking for a unix command using awk and grep that help me fetching a particular ip address and hostname from the host file.........??????

Hello,

Could you please provide us the input and expected output please for same.

Thanks,
R. Singh

You can do it directly with
grep -i <ip address> /etc/hosts

Not sure why you need to use awk. Please provide more details if you have any specific requirement.

Not sure why you would need -i with an IP address, but you would need it for an alphabetic host name search.

Do you want to get them into variables?

If you are searching for a name, you will need to use the -E flag and give a variety of strings to match, such as:-

  • First on line (IP address); followed by a space
  • First on line (IP address); followed by a tab
  • Preceded by space; last on line
  • Preceded by tab; last on line
  • Preceded by space; followed by a space
  • Preceded by space; followed by a tab
  • Preceded by tab; followed by a space
  • Preceded by tab; followed by a tab

You also need to trim off any comments that might be picked up by mistake too. Consider searching for prod this /etc/hosts file:-

100.100.100.1        host1      prod          # This is real production
200.200.200.2        host2      pre-prod      # This is not live yet.
300.300.300.3        host3      ex-prd        # This was prod for a bit

Remember that one IP address can have multiple host names associated with it in /etc/hosts. Try:-

cut -f 1 -d "#" /etc/hosts |  grep -Ei \
"^search-string |^search-string<tab>| search-string$|<tab>search-string$| search-string | search-string<tab>|<tab>search-string |<tab>search-string<tab>" | \
  read my_ip my_host1 my_host2 my_host2 my_host3 my_other_hosts

use the tab character where it shows <tab> rather than use that as a literal string.

The ^ indicates start of line.
The $ indicates end of line.
The | is a logical or between each of the possible searches.

Even then, I might not have considered everything, but if you are looking for information on other servers, it's best to use a name and let the server figure it out through DNS in any case. If you need to talk to a particular application, get a CNAME set up in DNS and refer to that, so that if you move the application, you redirect the CNAME entry and your code need toy change.

I hope that this helps,
Robin
Liverpool/Blackburn
UK