
현재 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이 아님)이 있는지 확인하고 싶습니다. 마지막으로 두 기준에 모두 일치하는 최상위 장치의 이름을 반환하고 싶습니다.
따라서 위의 예에서는 일치하는 항목 1개만 반환됩니다
/dev/sdc /dev/mapper/d1
.
/dev/sdc
하위 장치의 마운트 지점이 null이거나 비어 있기 때문에 장치가 반환되지 않습니다 .
나는 이미 지금까지 이것을 얻었습니다:
lsblk -Jpo NAME,FSTYPE,SIZE,MOUNTPOINT | jq -r '.blockdevices[] | select(.fstype == "crypto_LUKS") '
그러나 이는 crypto_LUKS 기준만 확인하고 하위 마운트 지점은 확인하지 않습니다. 또한 두 값만 인쇄하는 대신 전체 배열 항목을 인쇄합니다.
이 문제를 어떻게 해결할 수 있나요?
답변1
블록 장치의 이름과 null이 아닌 각 하위 마운트 지점을 탭으로 구분된 목록으로 가져오려면 다음을 수행하세요.
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"
}
]
}