我需要从树的任意深度的对象中删除一个字段
.xxx
,其中另一个字段 .myfield
与正则表达式匹配。
我知道如何匹配精准的内容:
walk(if type == "object" and .myfield == "my content" then del(.xxx) else . end)'
我了解正则表达式过滤器
select(.myfield | test(my regexp))
如何将该过滤器转换为布尔条件以在
if
子句中使用?
您可以在条件中使用
(.myfield | test("my regexp"))
,就像您可以使用 `.myfield == "my content" 一样。
因此:
jq -c '
walk(if type == "object" and
.myfield? != null and
(.myfield | test("my regexp"))
then del(.xxx)
else . end)
' <<'EOF'
{
"structure": {
"test-match": {
"myfield": "content that matches my regexp",
"xxx": "this should be deleted"
},
"test-nomatch": {
"myfield": "content that DOES NOT match the active expression",
"xxx": "this should not be deleted"
},
"test-invalid": {
"state": "no myfield exists at all",
"xxx": "this should not be deleted"
}
}
}
EOF
...正确地作为输出发出:
{
"structure": {
"test-match": {
"myfield": "content that matches my regexp"
},
"test-nomatch": {
"myfield": "content that DOES NOT match the active expression",
"xxx": "this should not be deleted"
},
"test-invalid": {
"state": "no myfield exists at all",
"xxx": "this should not be deleted"
}
}
}