Search code examples
bashsedgrepiptranslate

Translate numbers (IP address) inside a variable (bash)


My problem is that I'm having an IP address like 10.3.1.33 This IP address is inside a variable ip=10.3.1.33

Now I want to translate the 33 inside that IP address with a "*". The "33" can change, so that this number has to be automatically put somewhere in a variable or so..... I have no clue how to do that. Thanks for any advice :)


Solution

  • In your very specific case you could use:

    $ ip="10.3.1.33"
    $ printf "%s\n" "${ip/33/*}"
    10.3.1.*
    

    And to replace (remove) everything after the last period:

    $ ip="10.3.1.33"
    $ printf "%s\n" "${ip%.*}.*"
    10.3.1.33
    

    The later is POSIX compatible while the first is available in bash (among other shells)