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?
You can only do one substitution at a time, so you need to do it in two steps:
newinet=${inet/inetnum: /}
echo ${newinet/ - / }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With