Extract path name component in jq

Viewed 213

I have the following bash command

something something ... |
xargs -L 1 az aks list --subscription |
jq -r '.[] | "az aks get-credentials --name \(.name) --resource-group \(.resourceGroup) --subscription=\(.id)"'

This works except the final argument \(.id) is a string I need to substring using the following commands output embedded in the final output string

awk -F "/" '{print $3}' <<< "/subscriptions/I-need-Selecting/resourcegroups/blahblah/blahblah"

I cannot seem to get this command to execute in the outputted command - I cannot escape the " or ' in the awk effectively.

The output from the aks list --subscriptions command looks something like

[{"name": "foo", "resourceGroup": "bar", "subscription": "/subscriptions/I-need-Selecting/resourcegroups/blahblah/blahblah"},
... ]

Can anyone help?

1 Answers

If you are asking, given

bash$ echo '[{"name": "tarzan", "resourceGroup": "froup", "id": "/subscriptions/I-need-Selecting/resourcegroups/blahblah/blahblah" }]' |
> jq -r '.[] | "az aks get-credentials --name \(.name) --resource-group \(.resourceGroup) --subscription=\(.id)"'
az aks get-credentials --name tarzan --resource-group froup --subscription=/subscriptions/I-need-Selecting/resourcegroups/blahblah/blahblah

... how to reduce the "subscription" parameter to just a substring, try

jq '.[] |  "az aks get-credentials --name \(.name) --resource-group \(.resourceGroup) --subscription=\(.id | split("/")[3])"'

It's not impossible to run Awk here, but given that jq has much the same capabilities and a built-in JSON parser, it seems better to do this natively in jq.

Related