You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jq获取包含linux-image-amd64的所有父节点?

解决方法

你的问题出在未过滤值为字符串的节点,也没检查子键是否存在。第一个主机web-prode-01.example.de的值是错误信息字符串,而非包含子键的对象,直接访问其linux-image-amd64子键会返回null,干扰了结果输出。

获取所有符合条件的主机名

执行以下命令,先筛选出值为对象且包含linux-image-amd64子键的节点,再输出主机名:

jq -r 'keys[] as $k | select(.[$k] | type == "object" and has("linux-image-amd64")) | $k'

输出结果:

web-prode-04.example.de
lmrelaunch.example.de

同时输出主机名和对应的linux-image-amd64内容

如果需要同时展示主机名和子项详情,使用:

jq -r 'keys[] as $k | select(.[$k] | type == "object" and has("linux-image-amd64")) | "\($k)\n\(.[$k]."linux-image-amd64")"'

输出结果:

web-prode-04.example.de
{"old":"5.10.197-1","new":"5.10.205-2"}
lmrelaunch.example.de
{"old":"6.1.38-4~bpo11+1","new":"6.1.55-1~bpo11+1"}

原命令问题分析

原命令jq -r 'keys[] as $k | "\($k) \(.[$k]."linux-image-amd64")"'没有做类型校验,处理第一个字符串值节点时会返回null,导致输出多余的无效行,容易让你误以为只得到一个有效结果。通过select过滤后,就能精准得到预期的两个主机节点。

内容的提问来源于stack exchange,提问作者colttt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:09:51