Search code examples
bashipv4parameter-expansion

How to replace the last octet in an IP adress using Bash?


I have a variable that contains an IP address.

ip=192.165.12.30 

How can I replace the last octet with 0 so that it becomes as below?

ip=192.168.12.0

Solution

  • You can use a parameter expansion:

    $ ip=${ip%.*}.0
    $ echo "$ip"
    192.165.12.0