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.
Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.
Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.
Using the lstrip() function to remove single quotes from string in Python. The lstrip() function conveniently removes any leading characters in a string. We can utilize the lstrip() function to remove any single quotes that are at the beginning of the string.
To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.
awk -v RS='' -v OFS='","' 'NF { $1 = $1; print "\"" $0 "\"" }' file
Output:
"apple","banana","pineapple"
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With