1

Let's say I have a sentence like this

The quick, (brown, fox) jumps over, the (lazy, old, dog)

I want to replace all the commas , inside parentheses () to colons :, however commas that are not enclosed by parentheses should not be replaced. The output should be like

The quick, (brown: fox) jumps over, the (lazy: old: dog)

Notice that the number of commas and parentheses are not fixed in each sentence. How can use shell related tools (bash, sed, awk etc.) to achieve this result?

I have tried to use sed 's/[^(]*\(([^)]*)\)/\1/g; s/,/:/g' to make substitution to all matched groups, but not sure how to plug the results back to the original sentence.

etopylight
  • 1,239
  • 1
  • 10
  • 15

1 Answers1

2

If your actual Input_file is same as shown Input then following may help you in same.

awk -F"[)(]" '{for(i=2;i<=NF;i+=2){gsub(/,/,":",$i);$i="("$i")"}} 1'  Input_file

Output will be as follows.

The quick,  (brown: fox)  jumps over, the  (lazy: old: dog)
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93