5

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...

anubhava
  • 761,203
  • 64
  • 569
  • 643
blackwire
  • 53
  • 1
  • 1
  • 3
  • 1
    Its better to not use old and outdated back-tics, but instead use parentheses like this `IP=$(ifconfig.....)` – Jotne Aug 04 '14 at 12:43

4 Answers4

14

Use "cut" command with . delimiter:

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

CN now contains the last octet.

jacknad
  • 13,483
  • 40
  • 124
  • 194
Danilo Raspa
  • 795
  • 5
  • 5
9

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}'`
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

Shortcut:

read IP CN < <(exec ifconfig en0 | awk '/inet / { t = $2; sub(/.*[.]/, "", t); print $2, t }')
konsolebox
  • 72,135
  • 12
  • 99
  • 105
1

I would not use ifconfig to get the IP, rather use this solution, since it gets the IP needed to get to internet regardless of interface.

IP=$(ip route get 8.8.8.8 | awk '{print $NF;exit}')

and to get last octet:

last=$(awk -F. '{print $NF}' <<< $IP)

or get the last octet directly:

last=$(ip route get 8.8.8.8 | awk -F. '{print $NF;exit}')
Jotne
  • 40,548
  • 12
  • 51
  • 55