Nesousx Nesousx - 4 months ago 13
Linux Question

Converting a list to double quoted comma separated strings

I have a problem I can't seem able to fix by myself, nor by searching the internets.

I have a list, stored in a file, like this:

apple
banana
pineapple


And I would like each string to be in double quote, and comma separated, like this:

"apple","banana","pineapple"


Ideally, the last word of the list shouldn't have a comma after it, but this is not mandatory.

The idea behind this is to be able to create a JSON formatted document populated by a list of item stored in a plain text file.

Thanks a lot in advance.

Answer
awk -v RS='' -v OFS='","' 'NF { $1 = $1; print "\"" $0 "\"" }' file

Output:

"apple","banana","pineapple"