Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to break IP address stored in bash variable into octets

i've got a bash variable that contains an IP address (no CIDR or anything, just the four octets).

i need to break that variable into four separate octets like this:

$ip = 1.2.3.4; 
$ip1 = 1
$ip2 = 2
# etc

so i can escape the period in sed. is there a better way to do this? is awk what i'm looking for?

like image 220
brent saner Avatar asked Oct 19 '11 02:10

brent saner


2 Answers

You could use bash. Here's a one-liner that assumes your address is in $ip:

IFS=. read ip1 ip2 ip3 ip4 <<< "$ip"

It works by setting the "internal field separator" for one command only, changing it from the usual white space delimiter to a period. The read command will honor it.

like image 193
Rob Davis Avatar answered Sep 30 '22 18:09

Rob Davis


If you want to assign each octet to its own variable without using an array or a single variable with newline breaks (so you can easily run it through a for loop), you could use # and % modifiers to ${x} like so:

[ 20:08 jon@MacBookPro ~ ]$ x=192.160.1.1 && echo $x
192.160.1.1
[ 20:08 jon@MacBookPro ~ ]$ oc1=${x%%.*} && echo $o1
192
[ 20:08 jon@MacBookPro ~ ]$ x=${x#*.*} && echo $x
160.1.1
[ 20:08 jon@MacBookPro ~ ]$ oc2={x%%.*} && echo $o2
160
[ 20:08 jon@MacBookPro ~ ]$ x=${x#*.*} && echo $x
1.1
[ 20:08 jon@MacBookPro ~ ]$ oc3=${x%%.*} && echo $o3
1
[ 20:08 jon@MacBookPro ~ ]$ x=${x#*.*} && echo $x
1
[ 20:08 jon@MacBookPro ~ ]$ oc4=${x%%.*} && echo $oc4
1

[ 20:09 jon@MacBookPro ~ ]$ echo "$oc1\.$oc2\.$oc3\.$oc4"
192\.160\.1\.1

See this /wiki/Bash:_Append_to_array_using_while-loop
and more in this article.

like image 20
chown Avatar answered Sep 30 '22 18:09

chown