如何在jq的CSV导出中添加标头? [英] How to add a header to CSV export in jq?

查看:48
本文介绍了如何在jq的CSV导出中添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从jq 教程:

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' \
| jq -r -c '.[] | {message: .commit.message, name: .commit.committer.name} | [.[]] | @csv'

csv的导出效果很好,但顶部缺少标题:

Which does csv export well, but missing the headers as the top:

"Fix README","Nicolas Williams"
"README: send questions to SO and Freenode","Nicolas Williams"
"usage() should check fprintf() result (fix #771)","Nicolas Williams"
"Use jv_mem_alloc() in compile.c (fix #771)","Nicolas Williams"
"Fix header guards (fix #770)","Nicolas Williams"

如何在顶部添加标题(在本例中为message,name)? (我知道可以手动进行操作,但是如何在jq内完成操作?)

How can I add the header (in this case message,name) at the top? (I know it's possible manually, but how to do it within jq?)

推荐答案

基于安东对杰夫·梅卡多(Jeff Mercado)的回答,此摘要将获取第一个元素的属性的键名,并将它们作为数组输出在行之前,因此将它们用作标题.如果不同的行具有不同的属性,那么它将无法正常工作.再说一次,生成的CSV也不会.

Based on Anton's comments on Jeff Mercado's answer, this snippet will get the key names of the properties of the first element and output them as an array before the rows, thus using them as headers. If different rows have different properties, then it won't work well; then again, neither would the resulting CSV.

map({message: .commit.message, name: .commit.committer.name}) | (.[0] | to_entries | map(.key)), (.[] | [.[]]) | @csv

这篇关于如何在jq的CSV导出中添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆