Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify content inside quotation marks, BASH

Tags:

grep

bash

sed

awk

Good day to all,

I was wondering how to modify the content inside quotation marks and left unmodified the outside.

Input line:

,,,"Investigacion,,, desarrollo",,,

Output line:

,,,"Investigacion, desarrollo",,,

Initial try:

sed 's/\"",,,""*/,/g' 

But nothing happens, thanks in advance for any clue

like image 311
Another.Chemist Avatar asked Dec 21 '25 02:12

Another.Chemist


1 Answers

The idiomatic awk way to do this is simply:

$ awk 'BEGIN{FS=OFS="\""} {sub(/,+/,",",$2)} 1' file
,,,"Investigacion, desarrollo",,,

or if you can have more than one set of quoted strings on each line:

$ cat file
,,,"Investigacion,,, desarrollo",,,"foo,,,,bar",,,

$ awk 'BEGIN{FS=OFS="\""} {for (i=2;i<=NF;i+=2) sub(/,+/,",",$i)} 1' file
,,,"Investigacion, desarrollo",,,"foo,bar",,,

This approach works because everything up to the first " is field 1, and everything from there to the second " is field 2 and so on so everything between "s is the even-numbered fields. It can only fail if you have newlines or escaped double quotes inside your fields but that'd affect every other possible solution too so you'd need to add cases like that to your sample input if you want a solution that handles it.

like image 125
Ed Morton Avatar answered Dec 23 '25 01:12

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!