我有一个问题,我似乎无法自己解决,也没有通过search互联网。
我有一个列表,存储在一个文件,如下所示:
apple banana pineapple
我希望每个string都用双引号和逗号分开,就像这样:
"apple","banana","pineapple"
理想情况下,列表的最后一个字不应该有逗号,但这不是强制性的。
这背后的想法是能够创build一个JSON格式的文件,由存储在纯文本文件中的项目列表填充。
非常感谢。
awk -v RS='' -v OFS='","' 'NF { $1 = $1; print "\"" $0 "\"" }' file
输出:
"apple","banana","pineapple"
我认为Perl也值得一提:
perl -lne 'push @a, qq("$_") }{ print join(",", @a)' file
构建一个数组@a
其中包含每行的值,用双引号括起来。 然后,文件处理完毕后,打印出@a
中所有元素的逗号分隔列表。
由于-n
和-p
开关的实现方式,所谓的爱斯基摩语问候语}{
是用于创建END
块的简写。
输出:
"apple","banana","pineapple"
如果是你正在寻找的JSON,你可以使用encode_json
:
perl -MJSON -lne 'push @a, $_ }{ print encode_json(\@a)' file
这将数组转换为真正的JSON编码列表:
["apple","banana","pineapple"]
你也可以使用这个方法:
sed -r ':loop ; N ; s/\n/,/g ; $s/[^,]+/"&"/g ; t loop' filename
另一个awk
awk '{printf "\"%s\"",$1}' file | awk '{gsub(/""/,"\",\"")}1' "apple","banana","pineapple"
要么
awk '{printf "\"%s\"",$1}' file | sed 's/""/","/g'
没有花哨的东西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
前两行的特殊顺序很重要 – 它阻止了最后的逗号被追加。
sed
和paste
解决方案:
sed -e 's/^\|$/"/g' file | paste -s -d, -