2

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

2 Answers2

5

@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:]])}"
    
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
4

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563