replace space only between parentheses

awk, bash, regex, sed

Solution

Using sed:

sed ':l s/\(([^ )]*\)[ ]/\1_/;tl' input

If you have unbalanced parenthesis:

sed ':l s/\(([^ )]*\)[ ]\([^)]*)\)/\1_\2/;tl' input

Problem

In a string, I am trying to replace all spaces between parentheses by an underscore. For example, given `this ( is my ) simple example` I'd like to get `this (_is_my_) simple example`. I am working on the bash and thought of creating a substitution expression for sed, however I cannot come up with a simple one line solution. Looking forward to your help

Original source