Replace comma which is not inside brackets,quotes or paranthesis

Hi All,

I want to replace the commas which are not inside parenthesis,quotes

if input is

 abc,[def,ghi,ijk],lm,(no,pq,rs),{tu,vw,xy},zs,"as,as,fr",'ab,cd,ef'

output should be

 abc [def,ghi,ijk] lm (no,pq,rs) {tu,vw,xy} zs "as,as,fr" 'ab,cd,ef' 

I tried this str.replaceAll("\\(.*?\\)|(,)", " "); say my string is str, it will replace commas which are not inside ( ) but output will not have content inside ( )

Any help is highly appreciated

Thanks,
Pre

Hello Pre,

If input is exactly in same format in which you showed then following may help.

awk '{gsub(/,\[/," [",$0);gsub(/],/,"] ",$0);gsub(/,\(/," (",$0);gsub(/\), /,")",$0);gsub(/,\"/," \"",$0);gsub(/\",/,"\" ",$0);gsub(/,{/," {",$0);gsub(/},/,"} ",$0);;print}'   Input_file

Output will be as follows.

abc [def,ghi,ijk] lm (no,pq,rs) {tu,vw,xy} zs "as,as,fr" 'ab,cd,ef'

Thanks,
R. Singh

It looks like javascript question if my guess is true then try

<script>
var str="abc,[def,ghi,ijk],lm,(no,pq,rs),{tu,vw,xy},zs,\"as,as,fr\",'ab,cd,ef'";
console.log(str);
res = str.replace(/,(?=(?:"[^"]*"|\047[^\047]*\047|\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*}|[^"\047\[{}()\]])*$)/g, " ");
console.log(res);
</script>

Edit fiddle - JSFiddle

else try this

[akshay@localhost tmp]$ cat infile
abc,[def,ghi,ijk],lm,(no,pq,rs),{tu,vw,xy},zs,"as,as,fr",'ab,cd,ef'

[akshay@localhost tmp]$ perl -pe 's/,(?=(?:"[^"]*"|\047[^\047]*\047|\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*}|[^"\047\[{}()\]])*$)/ /g' infile
abc [def,ghi,ijk] lm (no,pq,rs) {tu,vw,xy} zs "as,as,fr" 'ab,cd,ef'

Try

awk     '       {for (i=1; i<=NF; i++)
                        {if ($i~/[[({]/) IN=1
                         if ($i~/[])}]/) IN=0
                         if ($i~/[\"\047]/)  IN=!IN
                         if (!IN && ($i==",")) $i=" "}
                        }
         1
        ' FS="" OFS="" file
abc [def,ghi,ijk] lm (no,pq,rs) {tu,vw,xy} zs "as,as,fr" 'ab,cd,ef' kl jm ke

---------- Post updated at 11:06 ---------- Previous update was at 11:05 ----------

or even

awk     '       {for (i=1; i<=NF; i++)
                        {if ($i~/[])}[({\"\047]/)  IN=!IN
                         if (!IN && ($i==",")) $i=" "}
                        }
         1
        ' FS="" OFS="" file