Replace multiple blanks within double quotes

I have various column names within double quotes, separated by commas.
Example:

"column one", "column number two", "this is column number three", anothercolumn, yetanothercolumn

I need to eliminate the double quotes and replace the blanks within the double quotes by underscores, giving:

column_one, column_number_two, this_is_column_number_three, anothercolumn, yetanothercolumn

Any occurrence of a double quoted string containing no blanks must remain untouched:

ex. "freddy" --> "freddy"

I have tried using sed but my results suggest that sed's 'greedy parsing' is getting in the way. Because of this, I had to repeatedly execute my sed script to get the desired result.

Thanks
JG

> cat inf
"column one", "column number two", "this is column number three", anothercolumn, yetanothercolumn

> cat inf | sed "s/, /,~/g" | tr " " "_" | sed "s/,~/, /g" | sed "s/\"//g"
column_one, column_number_two, this_is_column_number_three, anothercolumn, yetanothercolumn

Note that I changed the ", " to ",~" and then back again later. This was so I wouldn't delete that space character.

sed only

sed 's/", "/~/g;s/ /_/g;s/~/", "/g' file

The requirement regarding leaving double quotes around a field if there is no space is the difficult part. Try the following and please report back on how it worked out. I am sure there is a more efficient way of doing the work but this should work for you.

sed -e 's/",[^"]*"/,/g' -e 's/^"//' -e 's/"$//' -e 's/ /_/g' \
    -e 's/^\([^_]*\),/"\1",/g' -e 's/,\([^_]*\)$/,"\1"/g' -e 's/,\([^_]*\),/,"\1",/g' file

Hi,

Try this script, hope it helps you

tr "," "\n" < inp.txt > temp1.txt
sed -e '/ /s/^\"//g;/ /s/\"$//g' -e 's/ /_/g' temp1.txt > temp2.txt
paste -sd, temp2.txt
rm temp1.txt temp2.txt

Regards,
Chella

Thanks all for your responses. I will try these in a real-world scenario and report back.

Many thanks for your help

JG