Reputation: 73
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.
Upvotes: 7
Views: 4143
Reputation: 2142
sed
and paste
solution:
sed -e 's/^\|$/"/g' file | paste -s -d, -
Upvotes: 2
Reputation:
No fancy stuff awk:
awk 'x{x=x","}{x=x"\""$1"\""}END{print x}' file
Explained version:
awk '
out { out = out "," } # if there is already something in the output string, append a comma to it
{ out = out "\"" $1 "\"" } # always append the quoted first column of input to the output string
END { print out } # finally, print the output string
' file
The peculiar ordering of the first two lines matters - it prevents the final comma from being appended.
Upvotes: 0
Reputation: 5092
You can also use this method:
sed -r ':loop ; N ; s/\n/,/g ; $s/[^,]+/"&"/g ; t loop' filename
Upvotes: 1
Reputation: 74595
I think that Perl also deserves a mention:
perl -lne 'push @a, qq("$_") }{ print join(",", @a)' file
Builds an array @a
containing the value on each line, wrapped in double quotes. Then once the file has been processed, prints out a comma separated list of all the elements in @a
.
The so-called eskimo greeting }{
is a shorthand used to create an END
block, due to the way that the -n
and -p
switches are implemented.
Output:
"apple","banana","pineapple"
If it's JSON you're looking for, you could use encode_json
:
perl -MJSON -lne 'push @a, $_ }{ print encode_json(\@a)' file
This turns the array into a real JSON-encoded list:
["apple","banana","pineapple"]
Upvotes: 2
Reputation: 75478
awk -v RS='' -v OFS='","' 'NF { $1 = $1; print "\"" $0 "\"" }' file
Output:
"apple","banana","pineapple"
Upvotes: 7
Reputation: 41446
Another awk
awk '{printf "\"%s\"",$1}' file | awk '{gsub(/""/,"\",\"")}1'
"apple","banana","pineapple"
or
awk '{printf "\"%s\"",$1}' file | sed 's/""/","/g'
Upvotes: 0