24

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
  • 1,207
  • 7
  • 22
  • 36

2 Answers2

36

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

newinet=${inet/inetnum: /}
echo ${newinet/ - / }
benaryorg
  • 769
  • 1
  • 6
  • 20
Barmar
  • 669,327
  • 51
  • 454
  • 560
9

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
  • 446,329
  • 63
  • 468
  • 610