我目前正试图用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“。然后,对于这些设备,我想检查子设备(如果存在)是否有一个挂载点( null)。最后,我想返回符合这两个标准的toplevel设备的名称。
因此,对于上面的示例,只返回一个匹配:/dev/sdc /dev/mapper/d1。
由于子设备的挂载点为空/空,所以不会返回/dev/sdc设备。
到目前为止,我已经知道了:
lsblk -Jpo NAME,FSTYPE,SIZE,MOUNTPOINT | jq -r '.blockdevices[] | select(.fstype == "crypto_LUKS") '但这只是检查crypto_LUKS的标准,而不是孩子们的坐骑点。此外,它还会打印整个数组条目,而不仅仅是两个值。
我怎么才能解决这个问题?
发布于 2021-10-21 14:02:29
要将块设备的名称及其每个非空子挂载点作为制表符分隔的列表:
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,并且至少有一个具有字符串的mountpoint的children元素。
考虑到问题中的数据,这将返回
{
"name": "/dev/sdc",
"fstype": "crypto_LUKS",
"size": "100G",
"mountpoint": null,
"children": [
{
"name": "/dev/mapper/abc2",
"fstype": "btrfs",
"size": "100GG",
"mountpoint": "/mnt/test"
}
]
}https://unix.stackexchange.com/questions/674215
复制相似问题