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

I need to pull a substring from JSON. In the JSON document below, I need the end of the value jq '.[].networkProfile.networkInterfaces[].id'In other words, I just need to A10NICvw4konls2vfbw-datago to another command. I can't figure out how to pull a substring using grep. I see examples of regular expressions, but have not succeeded.

[
  {
    "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"
        }
      ]
    }
  }
]
+4
source share
3 answers

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

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

Try the following:

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

-r tells JQ to print the output in the form of "raw" - in this case, this means no double quotes around the string value.

jq, id, , ( jq) split("/") . , last (, @Thor) .

+3

If you want to do this with grep, this is one way:

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

Conclusion:

A10NICvw4konls2vfbw-data
+1
source

Source: https://habr.com/ru/post/1675558/


All Articles