10

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-data to 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.

[
  {
    "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"
        }
      ]
    }
  }
]
peak
  • 105,803
  • 17
  • 152
  • 177
Adoyt
  • 395
  • 2
  • 4
  • 17

3 Answers3

7

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

.[].networkProfile.networkInterfaces[].id | sub(".*/";"")
peak
  • 105,803
  • 17
  • 152
  • 177
7

Try this:

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

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

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

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
2

If you want to do it with grep here is one way:

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

Output:

A10NICvw4konls2vfbw-data
Thor
  • 45,082
  • 11
  • 119
  • 130