使用 jq 在 json 中进行类似正则表达式的搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31438087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:58:43  来源:igfitidea点击:

regex-like search in a json with jq

jsonregexbashjq

提问by mguerin

I have this json and I want to get the id of the corresponding subnet that fit the variable subnet.

我有这个 json,我想获取适合可变子网的相应子网的 id。

subnet="192.168.112"
json='{
  "subnets": [
    {
      "cidr": "192.168.112.0/24",
      "id": "123"
    },
    {
      "cidr": "10.120.47.0/24",
      "id": "456"
    }
  ]
}'

Since regex is not supported with jq. The only way I found to get the right id is to mixte grep, sed and jq like this :

由于 jq 不支持正则表达式。我发现获得正确 id 的唯一方法是像这样混合 grep、sed 和 jq:

tabNum=$((`echo ${json} | jq ".subnets[].cidr" | grep -n "$subnet" | sed "s/^\([0-9]\+\):.*$//"` - 1))
NET_ID=`echo ${json} | jq -r ".subnets[${tabNum}].id"`

Is there a way to get the id only using jq ?

有没有办法只使用 jq 获取 id ?

回答by

It's not completely clear to me what your provided script does, but it seems like it only looks for a string that contains the provided subset. I would suggest using containsor startswith. A sample script would look like:

我并不完全清楚您提供的脚本是做什么的,但它似乎只查找包含提供的子集的字符串。我建议使用containsstartswith。示例脚本如下所示:

echo "${json}" | jq --arg subnet "$subnet" '.subnets[] | select(.cidr | startswith($subnet)).id'

Since you mention regex: the latest release of jq, 1.5, includes regex support (thanks to Jeff Mercado for pointing this out!) and, if you have to deal with string manipulation problems frequently, I'd recommend checking it out.

既然您提到了正则表达式:jq 的最新版本 1.5 包括正则表达式支持(感谢 Jeff Mercado 指出这一点!)并且,如果您必须经常处理字符串操作问题,我建议您查看一下。