代码之家  ›  专栏  ›  技术社区  ›  einpoklum

从字段:值格式转换为CSV

  •  1
  • einpoklum  · 技术社区  · 6 年前

    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命令行的东西。

    1 回复  |  直到 6 年前
        1
  •  2
  •   aborruso    6 年前

    你好,伟大的磨坊主 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