Replace text in parentheses

Hi

I would like to replace a comma in parentheses to a semicolon for example. Other commas outside () stay unchanged. How can I do this?

aaaa,bbb,ccc,ddd(eee,fff,ggg),hhh,iii
to
aaaa,bbb,ccc,ddd(eee;fff;ggg),hhh,iii

Thanks

Hope this works for you.

sed is used to avoid spaces between "," (Commas)

If in the string there is only a couple of open/closed parenthesis:

echo "aaaa,bbb,ccc,ddd(eee,fff,ggg),hhh,iii" | \
awk -F'[()]' '{ gsub(",",";",$2); print($1"("$2")"$3) }'

This is a rapid solution. For sure there will be a more clever and general method to obtain the same :slight_smile:

Thanks a lot
The text in file can be dynamic.
aa,bb,cc
aa,bb,cc,dd,dfas,(dfd,d)df,df,afd
dafk
fads,df,dafa,dfa
a,d,d,f,g(1,1)fd

Another quick and dirt one:

awk '{
   s="";
   replace=0;
   for (i=1; i<=length($0); i++) {
      c=substr($0,i,1);
      if (c == "(") replace=1;
      if (c == ")") replace=0;
      if (c == "," && replace) { s=s";" } else { s=s c };
   }
   print s;
}' input_file

However, it doesn't work if you have unmatched parenthesis on lines!

Hi,

We can use awk string function GSUB to address this issue.

code:

nawk 'BEGIN{FS="[()]"}
{
gsub(/,/,";",$2)
printf("%s(%s)%s\n", $1,$2,$3)
}' file