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
Using sed:
sed ':l s/\(([^ )]*\)[ ]/\1_/;tl' input
If you have unbalanced parenthesis:
sed ':l s/\(([^ )]*\)[ ]\([^)]*)\)/\1_\2/;tl' input
$ cat file
this ( is my ) simple example
$ awk 'match($0,/\([^)]+\)/) {str=substr($0,RSTART,RLENGTH); gsub(/ /,"_",str); $0=substr($0,1,RSTART-1) str substr($0,RSTART+RLENGTH)} 1' file
this (_is_my_) simple example
put the match() in a loop if the pattern can occur multiple times on a line.
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