繁体   English   中英

从字段:值格式转换为CSV

[英]Converting from field: value format to CSV

我有一个以下格式的文件(嗯,有点):

RECORD_SEPARATOR
foo: some foo value
bar: another value
baz: 123
RECORD_SEPARATOR
foo: another foo value
bar: yet another value
baz: 345
RECORD_SEPARATOR
foo: a third foo
RECORD_SEPARATOR
bar: a fourth bar
baz: 111

等等。 这里的重点是,并非所有记录都具有所有字段。

我的问题:将数据转换为CSV格式的超级简单方法是什么? 那就是我的例子

foo,bar,baz
some foo value,another value,123
another foo value,yet another value,345
a third foo,,
,a fourth bar,111

当然,您可以为此编写awk(或perl或Python)脚本,但我希望预先存在一些东西,或者有一些技巧可以使它成为非常简短的脚本。

注意:我正在寻找的东西当然是面向Unix命令行的。

从伟大的Miller开始: http://johnkerl.org/miller/doc ,从

foo: some foo value
bar: another value
baz: 123

foo: another foo value
bar: yet another value
baz: 345

foo: a third foo

bar: a fourth bar
baz: 111

你可以跑

mlr --x2p --ips ": " --barred cat then unsparsify --fill-with "" inputFile

并有漂亮的打印输出

+-------------------+-------------------+-----+
| foo               | bar               | baz |
+-------------------+-------------------+-----+
| some foo value    | another value     | 123 |
| another foo value | yet another value | 345 |
| a third foo       | -                 | -   |
| -                 | a fourth bar      | 111 |
+-------------------+-------------------+-----+

如果要CSV,请运行

mlr --x2c --ips ": " cat then unsparsify --fill-with "" inputFile

你将有

foo,bar,baz
some foo value,another value,123
another foo value,yet another value,345
a third foo,,
,a fourth bar,111

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM