Multiple string replacements in bash

I have a variable called inet that contains the following line:

 inet="inetnum: 10.19.153.120 - 10.19.153.127" 

I would like to convert this line to the notation below:

 10.19.153.120 10.19.153.127 

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

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

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

+6
source share
2 answers

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

 newinet=${inet/inetnum: /} echo ${newinet/ - / } 
+8
source

Use regex in bash :

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

A regular expression may be more reliable, but should contain two IP addresses in the example string. Two capture groups are located at indices 1 and 2, respectively, of the array parameter BASH_REMATCH and are assigned to the newinet parameter.

+3
source

Source: https://habr.com/ru/post/975717/


All Articles