Tuesday, October 25, 2022

[SOLVED] How to remove last octet of an ip address in terminal?

Issue

Lets say I have an IP address of 123.456.789.01

I want to remove the last octet 123.456.789.01 but not the period.

So what I have left is 123.456.789.

Any help is appreciated. Thank you.

Linux Terminal

I tried isolating the final octet but that just gives me the last octet 01 not 123.456.789.:

$ address=123.456.789.01 
$ oct="${address##*.}"
$ echo "$oct"
01

Solution

With string manipulation, you cannot use lookarounds like in regex, but you can simply put the dot back once it is removed since it is a fixed pattern part.

You can use

#!/bin/bash
s='123.456.789.01'
s="${s%.*}."
echo "$s"
# => 123.456.789.

See the online demo.

Note that ${s%.*} removes the shortest string to the first . from the end of string.



Answered By - Wiktor Stribiżew
Answer Checked By - David Marino (WPSolving Volunteer)