I am sure you can also do this in sed
but it is much easier for me in Perl:
perl -pe 's/([^,])\"/$1xxx/g; s/xxx,/\",/g; s/xxx/\"\"\"/g' data.txt
EXPLANATION:
perl -pe
: execute the script given on the command line on each line of the input file
s/([^,])\"/$1xxx/g;
: substitute every occurrence of "
preceded by any non-comma character with a random string xxx
. This assumes that your data will never contain xxx
.
s/xxx,/\",/g;
: substitute those xxx
that are followed by a comma back to ",
.
s/xxx/\\\"/g
: replace the rest of the xxx
with escaped quotes \"
, these will be the "
that were in your data.
EXAMPLE:
$ cat test.txt
"data","da"t"a","data","data","foo "bar" foo", "data"
$ perl -pe 's/([^,])\"/$1xxx/g; s/xxx,/\",/g; s/xxx//g' test.txt
"data","data","data","data","foo bar foo","data
","
?