skip to Main Content

I’m stuck in using sed command.
I try to get my network address using sed command.
My host is like

$ hostname -I
192.168.11.12

I want to get only "192.168.11." from the address above.
I tried

hostname -I | sed -E  's/([0-9]{1,3}.)([0-9]{1,3}.)([0-9]{1,3}.)([0-9]{1,3})$/123/'

But it doesn’t work and I get

192.168.11.12

Even though

echo "192.168.11.12" | sed -E  's/([0-9]{1,3}.)([0-9]{1,3}.)([0-9]{1,3}.)([0-9]{1,3})$/123/'

works properly.
Does anyone know what is wrong?

My environment: Ubuntu 22.04.3 LTS

2

Answers


  1. It looks like the issue in your sed command is related to the regex pattern and how it’s applied.

    Try this

    hostname -I | sed -E 's/([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.).*/1/'
    

    and see if that helps

    Login or Signup to reply.
  2. You are overcomplicating things.

    hostname -I |
    sed 's/.[^.]*$//'
    

    as in, remove the last dot and all the text after it.

    The immediate problem with your attempt seems to have been the missing backslash before one dot, and/or the lack of a line-beginning anchor; though neither of those would be fatal if it weren’t for the fact that there is apparently some invisible text (a space? Or some control character?) at the end of the hostname output. Maybe pipe it to cat -v or od -tx1 to see exactly what it prints.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search