将列表转换为双引号逗号分隔的字符串

时间:2014-07-22 10:26:13

标签: linux awk sed grep

我有一个问题,我似乎无法通过自己解决,也无法搜索互联网。

我有一个列表,存储在一个文件中,如下所示:

apple
banana
pineapple

我希望每个字符串都是双引号,逗号分隔,如下所示:

"apple","banana","pineapple"

理想情况下,列表的最后一个单词后面不应该有逗号,但这不是强制性的。

这背后的想法是能够创建一个JSON格式的文档,该文档由存储在纯文本文件中的项目列表填充。

提前多多感谢。

6 个答案:

答案 0 :(得分:5)

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

输出:

"apple","banana","pineapple"

答案 1 :(得分:2)

我认为Perl值得一提:

perl -lne 'push @a, qq("$_") }{ print join(",", @a)' file

构建一个数组@a,其中包含每行的值,用双引号括起来。然后,在处理完文件后,打印出@a中所有元素的逗号分隔列表。

由于END-n开关的实现方式,所谓的eskimo greeting }{是用于创建-p块的简写。

输出:

"apple","banana","pineapple"

如果您正在寻找JSON,可以使用encode_json

perl -MJSON -lne 'push @a, $_ }{ print encode_json(\@a)' file

这会将数组转换为真正的JSON编码列表:

["apple","banana","pineapple"]

答案 2 :(得分:1)

您也可以使用此方法:

sed -r ':loop ; N ; s/\n/,/g ; $s/[^,]+/"&"/g ; t loop' filename

答案 3 :(得分:0)

另一个awk

awk '{printf "\"%s\"",$1}' file | awk '{gsub(/""/,"\",\"")}1'
"apple","banana","pineapple"

awk '{printf "\"%s\"",$1}' file | sed 's/""/","/g'

答案 4 :(得分:0)

没有花哨的东西awk:

awk 'x{x=x","}{x=x"\""$1"\""}END{print x}' file

解释版本:

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

前两行的特殊顺序很重要 - 它可以防止附加最后一个逗号。

答案 5 :(得分:0)

sedpaste解决方案:

sed -e 's/^\|$/"/g' file | paste -s -d, -