1

I have a list of words such as:

string1
string2
string3
....
string12312

How do I convert them these words in such manner that output could be used as a JS array, i.e. "String1", "String2"..., "String12312" --- in other words how do I add quotation marks and commas? I understand this an be done in shell, but I guess any other solution would be okay as long as the result can be converted into an array.

  • This "list of words", where are they? in a file? a variable? – glenn jackman Dec 24 '15 at 15:50
8

Here's one way:

sed 's/^\|$/"/g' file | paste -d, -s
"string1","string2","string3","....","string12312"
  • 6
    Or its POSIX equivalent: sed 's/.*/"&"/' file | paste -sd , - – Stéphane Chazelas Dec 24 '15 at 17:01
2

If you don't affraid the comma at the end of line you can use

printf '"%b", ' $(<file)

which outputs

"string1", "string2", "string3", "....", "string12312",
  • (assuming $IFS has its default value and those strings don't contain any of those $IFS characters, and that they don't contain globbing characters. That's one case where you're using the split+glob operator but forgot to tune it to your need). – Stéphane Chazelas Dec 24 '15 at 22:41
2

Using Awk:

awk '{printf "\"%s\", ", $0}' file
  • you answered it too! so merry christmas again! – mikeserv Dec 25 '15 at 0:04
2
xargs printf '"%s", ' <file

...will work with your example data:

"string1", "string2", "string3", "....", "string12312",
  • 1
    Merry Christmas, sed maniac! :) – jasonwryan Dec 24 '15 at 23:55
  • @jasonwryan - i rather like that one. it's catchy. and it beats asshole. and to you, anyway. – mikeserv Dec 24 '15 at 23:59
1

Could always just turn it into a JSON array:

#!/usr/bin/env perl
use strict;
use warnings;

use JSON;

chomp ( my @data = <DATA> ); 
print to_json ( \@data );

__DATA__
string1
string2
string3
string12312

Or as a one liner:

perl -MJSON -e 'print to_json ( [map{s/\n//gr}<>] )'

Pipe on stdin or specify a filename (like grep/awk etc.)

Both output (the latter when fed your example):

["string1","string2","string3","string12312"]

Can format it as 'pretty' JSON with print to_json ( \@data, {pretty=>1}) which'll add linefeeds and indentation.

(that one liner above is based on a newer perl that you might have installed. If that doesn't work: perl -MJSON -e 'chomp(@a=<>);print to_json ( \@a )'

  • You probably want chomp(@a = <>) in the oneliner – glenn jackman Dec 24 '15 at 17:27
  • Yes, true. Although I've had a slightly better idea. – Sobrique Dec 24 '15 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.