bashsedhostnamehosts-file

using bash with sed how to extract ip from a hostname command and saving it in /etc/hosts file


I want to store an entry in the /etc/hosts file for the IP of the box that I am on.

When I run the following command I get:

:-$ hostname
ip-10-55-9-102

I want to store this entry in /etc/hosts as following:

Expected result: 10.55.9.102 ip-10-55-9-102

I tried but so far....

CURRENT SOLUTION:

ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//+([.:])/-}" >> /etc/hosts

Actual result: 10.55.9.102 ip-10.55.9.102

Note: Expected has "-" and Actual has "." between numbers.


Solution

  • Your logic is good, but you don't use the correct pattern in your string substitution. You should have written the following :

    ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//[.:]/-}" >> /etc/hosts