Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list to double quoted comma separated strings

Tags:

linux

grep

sed

awk

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.

like image 465
Nesousx Avatar asked Jul 22 '14 10:07

Nesousx


People also ask

How do you convert lists into comma separated values?

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.

How can I convert comma separated string into a list 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.

How do I remove a single quote from a list?

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.

How do you mention double quotes in a 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.


2 Answers

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

Output:

"apple","banana","pineapple"
like image 135
konsolebox Avatar answered Oct 02 '22 11:10

konsolebox


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"]
like image 28
Tom Fenech Avatar answered Oct 02 '22 10:10

Tom Fenech