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

15,804

Solution 1

Shortcut:

read IP CN < <(exec ifconfig en0 | awk '/inet / { t = $2; sub(/.*[.]/, "", t); print $2, t }')

Solution 2

Use "cut" command with . delimiter:

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

CN now contains the last octet.

Solution 3

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}'`

Solution 4

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}')
Share:
15,804
Admin
Author by

Admin

Updated on June 09, 2022

Comments

  • Admin
    Admin almost 2 years

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

  • Jotne
    Jotne over 9 years
    You can shorten it some to:CN=$(cut -d. -f4 <<<$IP)
  • Admin
    Admin over 9 years
    Shorter using awk cn=$(awk -F. '$0=$4' <<< $ip)
  • anubhava
    anubhava over 9 years
    @Jidder: I believe only BASH supports <<< that's why I used pipes in non BASH solutions.
  • Admin
    Admin over 9 years
    Oh okay,didn't know it was specific to bash, is $() bash specific as well ?
  • chepner
    chepner over 9 years
    No, $(...) is in the POSIX standard.
  • chepner
    chepner over 9 years
    <<< is non-standard and not supported by all shells.
  • chepner
    chepner over 9 years
    <( ... ) is non-standard and not supported by all shells.
  • anubhava
    anubhava over 9 years
    Ah that is correct, thank for correcting @chepner me. Always helpful.