Saffik
Saffik

Reputation: 1013

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.

Upvotes: 2

Views: 987

Answers (4)

Ivan
Ivan

Reputation: 7317

There is a system var $HOSTNAME which is the same as hostname command. So if your hostname contain an ip address you can do this:

ip=${HOSTNAME//ip-} # create 'ip' var from $HOSTNAME and remove 'ip-'
ip=${ip//-/.}       # change '-' to '.' in 'ip' var
printf "$ip\t$HOSTNAME" >> /etc/hosts # add desired string to /etc/hosts

Or using hostname to get ip:

ip=( $(hostname -I) )
printf "$ip\t$HOSTNAME" >> /etc/hosts

Upvotes: 0

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10133

With plain bash:

ip=$(hostname -I)
ip=${ip%%[[:space:]]*}
printf "%s\tip-%s\n" "$ip" "${ip//./-}" # >> /etc/hosts

Drop the # if it works as intended.

Upvotes: 0

Hai Vu
Hai Vu

Reputation: 40783

How about using awk?

hostname | awk -F- '{printf "%s.%s.%s.%s %s\n", $2, $3, $4, $5, $0}' >> /etc/hosts

The awk command uses the -F- flag to specify the dash as a field separator. The printf command picks out fields #2, 3, 4, 5, along with $0 which is the whole line.

Upvotes: 1

Aserre
Aserre

Reputation: 5072

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

Upvotes: 2

Related Questions