簡體   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