Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple substitutions on a string in bash [duplicate]

Tags:

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?

like image 285
Martin Avatar asked Sep 23 '14 13:09

Martin


2 Answers

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

newinet=${inet/inetnum: /}
echo ${newinet/ - / }
like image 162
Barmar Avatar answered Sep 24 '22 18:09

Barmar


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.

like image 45
chepner Avatar answered Sep 22 '22 18:09

chepner