LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Quick sed question (https://www.linuxquestions.org/questions/programming-9/quick-sed-question-756716/)

ColInvictus 09-21-2009 04:37 AM

Quick sed question
 
I have a series of files in the format:

{"field(1)":"value(1)","field(2)":"value(2), ... ,"field(n)","value(n)"}

Which I'm trying to split using sed to have each field/value pair on on line:

sed -e '1s/^.//' -e '$s/.$//' -e 's/,/\n/g'

So far so simple, but some of the values might have commas in them, which means they'll be split up. Is there a way to change this so that only commas not within quotes will be replaced with \n? (e.g. make sed count number of " and if it finds a , after counting an odd number of " then ignore it?)

Thanks
Col

slakmagik 09-21-2009 04:45 AM

If it's exactly that, then you can replace runs of "," with "\n" and that will only match those commas between quotes rather than inside them.

Code:

:cat data
{"field(1)":"value(1)","field(2)":"value(2)","field(n)":"value(n)","field(z)":"comma,stuff"}

:sed -e '1s/^.//' -e '$s/.$//' -e 's/","/"\n"/g' data
"field(1)":"value(1)"
"field(2)":"value(2)"
"field(n)":"value(n)"
"field(z)":"comma,stuff"

Of course, if the data isn't that exact, then that may not work.

ColInvictus 09-21-2009 05:04 AM

I never thought of that... Thanks!


All times are GMT -5. The time now is 03:40 AM.