Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolate the last octet from an IP address and put it in a variable

The following script:

IP=`ifconfig en0 inet | grep inet | sed 's/.*inet *//; s/ .*//'`

isolates the IP address from ipconfig command and puts it into the variable $IP. How can I now isolate the last octet from the said IP address and put it in a second variable - $CN

for instance:

$IP = 129.66.128.72 $CN = 72 or $IP = 129.66.128.133 $CN = 133...

like image 398
blackwire Avatar asked Nov 28 '22 07:11

blackwire


2 Answers

Use "cut" command with . delimiter:

IP=129.66.128.72
CN=`echo $IP | cut -d . -f 4`

CN now contains the last octet.

like image 143
Danilo Raspa Avatar answered Dec 05 '22 16:12

Danilo Raspa


In BASH you can use:

ip='129.66.128.72'
cn="${ip##*.}"
echo $cn
72

Or using sed for non BASH:

cn=`echo "$ip" | sed 's/^.*\.\([^.]*\)$/\1/'`
echo $cn
72

Using awk

cn=`echo "$ip" | awk -F '\\.' '{print $NF}'`
like image 26
anubhava Avatar answered Dec 05 '22 17:12

anubhava