我目前正在尝试使用 jq 解析 lsblk 的输出,并根据某些标准对其进行过滤。
给出以下示例输出:
{
"blockdevices": [
{
"name": "/dev/sda",
"fstype": null,
"size": "931.5G",
"mountpoint": null,
"children": [
{
"name": "/dev/sda1",
"fstype": "ntfs",
"size": "50M",
"mountpoint": null
},{
"name": "/dev/sda2",
"fstype": "ntfs",
"size": "439.8G",
"mountpoint": null
},{
"name": "/dev/sda3",
"fstype": "vfat",
"size": "512M",
"mountpoint": "/boot/efi"
},{
"name": "/dev/sda4",
"fstype": "ext4",
"size": "491.2G",
"mountpoint": "/"
}
]
},{
"name": "/dev/sdb",
"fstype": "crypto_LUKS",
"size": "200GG",
"mountpoint": null,
"children": [
{
"name": "/dev/mapper/d1",
"fstype": "btrfs",
"size": "200G",
"mountpoint":[
null
]
}
]
},{
"name": "/dev/sdc",
"fstype": "crypto_LUKS",
"size": "100G",
"mountpoint": null,
"children": [
{
"name": "/dev/mapper/abc2",
"fstype": "btrfs",
"size": "100GG",
"mountpoint": "/mnt/test"
}
]
}
]
}
我想检查所有具有 fstype“crypto_LUKS”的顶级设备。然后,对于这些设备,我想检查子设备(如果存在)是否有安装点(不为空)。最后,我想返回符合这两个条件的顶级设备的名称。
因此对于上面的例子,只会返回 1 个匹配项:
/dev/sdc /dev/mapper/d1
。
该/dev/sdc
设备不会被返回,因为子设备的安装点为空。
到目前为止我已经得到了这个:
lsblk -Jpo NAME,FSTYPE,SIZE,MOUNTPOINT | jq -r '.blockdevices[] | select(.fstype == "crypto_LUKS") '
但这仅检查 crypto_LUKS 标准,而不检查子项的挂载点。此外,它确实打印整个数组条目,而不仅仅是两个值。
我该如何解决这个问题?
答案1
要以制表符分隔列表的形式获取块设备的名称及其每个非空子挂载点:
jq -r '
.blockdevices[] | select(.fstype == "crypto_LUKS") as $dev |
$dev.children[]? | select(.mountpoint | type == "string") as $mp |
[ $dev.name, $mp.name ] | @tsv'
由于“空挂载点”实际上并不是null
单个值的数组null
,因此我正在测试挂载点是否是字符串。
鉴于问题中的数据,这将返回
/dev/sdc /dev/mapper/abc2
要获取满足条件的块设备对象(如果这就是您所说的“整个数组”的意思):
jq '.blockdevices[] |
select(.fstype == "crypto_LUKS" and
any(.children[]?; .mountpoint | type == "string"))'
这将返回具有该fstype
值crypto_LUKS
并且至少有一个带有字符串的children
元素的块设备对象。mountpoint
鉴于问题中的数据,这将返回
{
"name": "/dev/sdc",
"fstype": "crypto_LUKS",
"size": "100G",
"mountpoint": null,
"children": [
{
"name": "/dev/mapper/abc2",
"fstype": "btrfs",
"size": "100GG",
"mountpoint": "/mnt/test"
}
]
}