2014-07-22 226 views
5

我有一个问题,我似乎无法自己修复,也没有通过搜索互联网。转换列表为双引号逗号分隔字符串

我有一个列表,保存在一个文件中,就像这样:

apple 
banana 
pineapple 

而且我想每个字符串是在双引号和逗号分隔,例如:

"apple","banana","pineapple" 

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

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

非常感谢。

回答

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

输出:

"apple","banana","pineapple" 
+0

大非常感谢!我在这里尝试了类似于另一个线程的东西,但无法使其工作。您的解决方案完美运作。 – Nesousx

+0

@Nesousx我加了一个小小的调整来确保周围有确实的字段。不客气:) – konsolebox

+1

'$ 1 = $ 1'做什么? –

0

另一个awk

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

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

我觉得是Perl也值得一提:

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

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

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

输出:

"apple","banana","pineapple" 

如果这是你要找的JSON,你可以使用encode_json

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

这会把数组转换成一个真正的JSON编码的列表:

["apple","banana","pineapple"] 
+0

'} {'是一个有趣的技巧,但是应该为新手读者的利益澄清,它只是'-p'的一个副作用,用'{}'包装表达式,而不是某种关键字,本身 –

+1

@Josip我编辑添加一点点关于。 –

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 

的前两行的事项的特有顺序 - 它防止最终逗号被追加。

1

您也可以使用这个方法:

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

sedpaste解决方案:

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