-1
echo $HOSTNAME

gives me ip-255-25-255-255. I am trying to remove ip- and replace - with ..

I can do:

a=${HOSTNAME#*-}
b=${a//-/.}

which gives me 255.25.255.255.

Is there any way I can do this in one line?

Dan R
  • 71
  • 7
  • 3
    Doing it in one line but calling an external tool is much more expensive than doing it in pure Bash on two lines. And if the line count is really that important, you can just put things on one line with `a=${HOSTNAME#*-} && echo "${a//-/.}"`. – Benjamin W. Dec 19 '18 at 15:50
  • What I wanted to get out of this was something like `b=${${HOSTNAME#*-}//-/.}`. This obviously doesn't work, but is there a solution like this possible? – Dan R Dec 19 '18 at 15:55
  • 1
    Not in Bash, I'd say. – Benjamin W. Dec 19 '18 at 15:56
  • There are some options [here](https://stackoverflow.com/questions/917260/can-var-parameter-expansion-expressions-be-nested-in-bash), things like [the command substitution](https://stackoverflow.com/a/35490880/3266847) boil down to what you're already doing, just less readable. – Benjamin W. Dec 19 '18 at 15:57
  • "In one line" is really kind of meaningless. Since you are assigning a variable here, it's going to be used in another line anyway. You could always do `ip=$( a=${HOSTNAME#*-}; echo "${a//-/.}" )`, which is one line and still *might* be better than executing a `sed` or `awk` even though it spawns a subshell, but why is it so important not to take an extra line to let the parser do th work for you? Or you could say `ip=${HOSTNAME#*-}` and when you use it do so as `${ip//-/.}`. Is there really much difference? – Paul Hodges Dec 19 '18 at 16:13

2 Answers2

1

Yes there is.

sed 's/^[^-]*-//;s/-/./g' <<< "$HOSTNAME"

yields the desired output.

  • s/^[^-]*-// matches zero or more non-dash characters followed by a dash (see it online) and removes them,
  • s/-/./g replaces all dashes with dots.
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • @PS. You're welcome. Don't you think that awk is a bit overkill for this trivial task? – oguz ismail Dec 19 '18 at 15:52
  • 1
    Its is, the first answer that come to mind is the one you already posted here. No harm in having different approach listed at one place for one task. I feel sed is natural solution to this question. – P.... Dec 19 '18 at 15:53
0

Using gsub function of awk:

echo 'ip-255-25-255-255' |awk '{gsub(/^[^-]+-/,"");gsub(/-/,".")}1'
255.25.255.255
P....
  • 17,421
  • 2
  • 32
  • 52