简体   繁体   中英

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

Use "cut" command with . delimiter:

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

CN now contains the last octet.

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

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

捷径:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM