32

I have a variable named inet which contains the following string:

inet="inetnum:        10.19.153.120 - 10.19.153.127"

I would like to convert this string to notation below:

10.19.153.120 10.19.153.127

I could easily achieve this with sed 's/^inetnum: *//;s/^ -//', but I would prefer more compact/elegant solution and use bash. Nested parameter expansion does not work either:

$ echo ${${inet//inetnum: /}// - / }
bash: ${${inet//inetnum: /}// - / }: bad substitution
$ 

Any other suggestions? Or should I use sed this time?

Martin
  • 957
  • 7
  • 25
  • 38

2 Answers2

41

You can only do one substitution at a time, so you need to do it in two steps:

newinet=${inet/inetnum: /}
echo ${newinet/ - / }
benaryorg
  • 915
  • 1
  • 8
  • 21
Barmar
  • 741,623
  • 53
  • 500
  • 612
11

Use a regular expression in bash as well:

[[ $inet =~ ([0-9].*)\ -\ ([0-9].*)$ ]] && newinet=${BASH_REMATCH[@]:1:2}

The regular expression could probably be more robust, but should capture the two IP addresses in your example string. The two captures groups are found at index 1 and 2, respectively, of the array parameter BASH_REMATCH and assigned to the parameter newinet.

chepner
  • 497,756
  • 71
  • 530
  • 681