bash Linux CLI - 如何从 JSON jq + grep 获取子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43595121/
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-18 16:03:49  来源:igfitidea点击:

Linux CLI - How to get substring from JSON jq + grep?

jsonbashgrepjqpathname

提问by Adoyt

I need to pull a substring from JSON. In the JSON doc below, I need the end of the value of jq '.[].networkProfile.networkInterfaces[].id'In other words, I need just A10NICvw4konls2vfbw-datato pass to another command. I can't seem to figure out how to pull a substring using grep. I've seem regex examples out there but haven't been successful with them.

我需要从 JSON 中提取一个子字符串。在下面的 JSON 文档中,我需要值的结尾jq '.[].networkProfile.networkInterfaces[].id'换句话说,我只A10NICvw4konls2vfbw-data需要传递给另一个命令。我似乎无法弄清楚如何使用 grep 拉出子字符串。我似乎有正则表达式的例子,但没有成功。

[
  {
    "id": "/subscriptions/blah/resourceGroups/IPv6v2/providers/Microsoft.Compute/virtualMachines/A10VNAvw4konls2vfbw",
    "instanceView": null,
    "licenseType": null,
    "location": "centralus",
    "name": "A10VNAvw4konls2vfbw",
    "networkProfile": {
      "networkInterfaces": [
        {
          "id": "/subscriptions/blah/resourceGroups/IPv6v2/providers/Microsoft.Network/networkInterfaces/A10NICvw4konls2vfbw-data",
          "resourceGroup": "IPv6v2"
        }
      ]
    }
  }
]

采纳答案by peak

In your case, sub(".*/";"")will do the trick as * is greedy:

在你的情况下,sub(".*/";"")会这样做,因为 * 是贪婪的:

.[].networkProfile.networkInterfaces[].id | sub(".*/";"")

回答by Mark Reed

Try this:

尝试这个:

jq -r '.[]|.networkProfile.networkInterfaces[].id | split("/") | last'

The -rtells JQ to print the output in "raw" form - in this case, that means no double-quotes around the string value.

-r告诉JQ打印在“原始”的形式输出-在这种情况下,周围的字符串值,意味着没有双引号。

As for the jqexpression, after you access the idyou want, piping it (still inside jq) through split("/")turns it into an array of the parts between slashes. Piping that through the lastfunction (thanks, @Thor) returns just the last element of the array.

至于jq表达式,在你访问id你想要的之后,管道它(仍然在里面jq)通过split("/")把它变成一个斜线之间的部分的数组。通过last函数传递它(谢谢,@Thor)只返回数组的最后一个元素。

回答by Thor

If you want to do it with grephere is one way:

如果你想这样做,grep这是一种方法:

jq -r '.[].networkProfile.networkInterfaces[].id' | grep -o '[^/]*$'

Output:

输出:

A10NICvw4konls2vfbw-data