【问题标题】:JQ to search for a regexJQ 搜索正则表达式
【发布时间】:2021-10-20 21:15:57
【问题描述】:

我有以下来自 curl 输出的 JSON,我需要检索其主机名中包含 wknhost_name(主机)的数量。在下面的 json 中,我们有两个主机,它们的 host_name 中有 wkn

{
  "href": "http://10.10.0.10:8080",
  "Hosts": {
    "cluster_name": "test",
    "host_name": "testmasternode.example.test.com",
    "ip": "10.10.0.10"
  }
}
{
  "href": "http://10.10.0.10:8080",
  "Hosts": {
    "cluster_name": "test",
    "host_name": "testwkn01.example.test.com",
    "ip": "10.10.0.11"
  }
}
{
  "href": "http://10.10.0.10:8080",
  "Hosts": {
    "cluster_name": "test",
    "host_name": "testwkn02.example.test.com",
    "ip": "10.10.0.12"
  }
}

我尝试了几种方法

  1. 这不会给出任何输出
curl -sH http://10.10.0.10:8080/api/v1/clusters/test/hosts?fields=Hosts/host_name,Hosts/ip \
| jq -r '.items | .[] | select(.Hosts.host_name == ("*wkn01.*"))' 
  1. 这会出错
curl -sH http://10.10.0.10:8080/api/v1/clusters/test/hosts?fields=Hosts/host_name,Hosts/ip  \
| jq -r '.items | .[] | select(.Hosts.host_name | match("*wkn01.*"))'
jq: error (at <stdin>:76): Regex failure: target of repeat operator is not specified

【问题讨论】:

  • *wkn01.* 不是有效的正则表达式。第一个 * 需要说明要重复的内容。

标签: json curl jq


【解决方案1】:

使用test 而不是match,因为您只需要一个布尔结果。然后,要测试是否有任何项目“在其host_name 中有wkn”,正则表达式wkn 就足够了。最后,当您“需要检索host_name 的数量”时,只需使用length 完成(它需要一个数组,因此我还将.[] 更改为map)。

... | jq -r '.items | map(select(.Hosts.host_name | test("wkn"))) | length'
2

【讨论】:

  • 谢谢,@pmf。它奏效了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 2023-04-10
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多