Home > Enterprise >  How to remove last octet of an ip address in terminal?
How to remove last octet of an ip address in terminal?

Time:10-26

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

CodePudding user response:

@WiktorStribiżew has the right answer.

A couple of other (more esoteric) techniques:

  • since ${address##*.} removes up to the last dot, leaving the octet, we can remove that from the end of the string:

    echo "${address%${address##*.}}"    # => 123.456.789.
    
  • using the extglob shell option, we enable extended patterns and can remove the longest sequence of one or more digits from the end of the string

    shopt -s extglob
    echo "${address%% ([0-9])}"
    # or, with a POSIX character class
    echo "${address%% ([[:digit:]])}"
    

CodePudding user response:

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.

  • Related