This snippet surely can be improved, but it should do the job:
hostname=ip-10-114-152-134.valter.henrique.com
hostip=$(echo ${hostname%%.*} | sed -e 's/ip-//' -e 's/-/./g')
${hostname%%.*}
removes everything after (and including) the first .
; sed
then removes the starting ip-
and replaces then the dashes with dots.
You can also use only one sed
command:
echo ip-10-114-152-134.valter.henrique.com | sed 's/ip-\(.*\)-\(.*\)-\(.*\)-\(.*\)\.valter\.henrique\.com/\1.\2.\3.\4/'
The regex in the first brackets (you need to escape these: \(.*\)
) gets assigned to \1
and so on.
Here is the last variant, using only bash functions:
IFSsave="$IFS"; IFS=- # save IFS prior modifying it
hostip=""
hostname=ip-10-114-152-134.valter.henrique.com # initial values
hostname=${hostname#*-} # remove the "ip-" part
hostname=${hostname%%.*} # remove the ".valter.henrique.com" part
for i in $hostname; do # loop over 10-114-152-134, splitted at "-" ($IFS)
hostip="${hostip}${i}." # append number. to $hostip
done
hostip=${hostip%.} # remove trailing dot
echo $hostip # print resulting IP
IFS="$IFSsave" # restore IFS
2To clarify,
ip-10-114-152-134.valter.henrique.com
is the "weird hostname" Amazon gives you, and you want to extract the IP address from it? – Daniel Beck – 2013-05-11T08:25:22.397Couldn't you just ping the hostname? – slhck – 2013-05-11T08:44:06.567
1@slhck If you're talking about getting the IP from a hostname via a DNS lookup, that's more for
nslookup
(ordig
orhost
). – Bob – 2013-05-11T09:20:03.220