Saturday, August 23, 2008

Subdivide an ip address - awk and eval


The purpose is quite simple! We need to assign each field in an IP address to separate variables.

e.g.

$
IP="172.21.60.1"

The way:

$ eval $(echo "$IP" | awk '{print "IP1="$1";IP2="$2";IP3="$3";IP4="$4}' FS=.)

So, just to confirm.

$ echo $IP1
172

$ echo $IP2
21

$ echo $IP3
60

$ echo $IP4
1

Making it more generic:

$ eval $(echo "$IP" | awk '{for(i=1;i<=NF;i++) printf "IP%s=%s\n",i,$i}' FS=.)

Related post: awk and eval

2 comments:

dmw said...

since you're using bash, you don't need awk and eval

IP="12.13.14.15"
set ${IP//./ }
echo "$1 - $2 - $3 - $4"
12 - 13 - 14 - 15

or if you don't want to use 'set' (want to preserve cmdline args)

ary=(${IP//./ })
echo "${ary[0]} ; ${ary[1]} ; ${ary[2]} ; ${ary[3]}"
12 ; 13 ; 14 ; 15

Jadu Saikia said...

@dmw, thanks for the bash solution.

© Jadu Saikia www.UNIXCL.com