Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace space only between parentheses

Tags:

regex

bash

sed

awk

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

like image 777
joerhau Avatar asked Jan 02 '13 22:01

joerhau


2 Answers

Using sed:

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

If you have unbalanced parenthesis:

sed ':l s/\(([^ )]*\)[ ]\([^)]*)\)/\1_\2/;tl' input
like image 175
perreal Avatar answered Oct 09 '22 06:10

perreal


$ 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.

like image 40
Ed Morton Avatar answered Oct 09 '22 06:10

Ed Morton