Better way to convert IP?

I am trying to convert 10.AB.C9.XYZ to 10.AB.C2.252.

Right now I am extracting each character and piecing them together.

ip_main=10.AB.C9.XYZ

A_char=${ip_main:3:1}
B_char=${ip_main:4:1}
C_char=${ip_main:6:1}

new_ip="10.${A_char}${B_char}.${C_char}2.252"

Is there a better way to accomplish this?

Answers 3

  • If all you want to do is to replace the last digit of the third octet and the whole of the fourth octet with 2.252, then you may do that with

    new_ip=${ip_main%?.*}2.252
    

    This deletes the shortest suffix string from $ip_main that matches ?.*, and then appends 2.252 to the result of that. The substitution with this pattern will always affect the last digit of the third octet, the dot between the 3rd and 4th octets, and then the whole 4th octet.

    Testing:

    $ ip_main=10.AB.C9.XYZ
    $ new_ip=${ip_main%?.*}2.252
    $ printf '%s\n' "$new_ip"
    10.AB.C2.252
    

  • You can subtract 7 from the third octet, and replace the fourth:

    echo 10.11.19.44 | awk -F. '{OFS=FS; print $1,$2,$3-7,252}'
    10.11.12.252
    

    This process would work most efficiently if you had a list of IP addresses to change.



Related Questions