Home > Back-end >  Compare two JSON arrays and iterate over the remaining items
Compare two JSON arrays and iterate over the remaining items

Time:06-18

I have two arrays with numbers that are already stored in variables:

$SLOT_IDS = [1,2,3,4,5]
$PR_IDS = [3,4]

I would like to find which numbers are in array 1 but not array 2. So in this case it would be

$OBSOLETE_SLOT_IDS = [1,2,5]

and then I would like to run a command foreach of those numbers and insert it into a placeholder:

So this command:

az webapp deployment slot delete -g group --name webapp --slot pr-<PLACEHOLDER>

Should be run three times:

az webapp deployment slot delete -g group --name webapp --slot pr-1
az webapp deployment slot delete -g group --name webapp --slot pr-2
az webapp deployment slot delete -g group --name webapp --slot pr-5

I know that should look something like this (it is required that it is inline):

for i in $OBSOLETE_SLOT_IDS; do az webapp deployment slot delete -g group --name webapp --slot pr-$i; done

So my questions:

  1. How can I calculte $OBSOLETE_SLOT_IDS from the other two variables with an inline command
  2. What is the correct version of the for loop

comment: seems that the variables do not contain actual arrays. They are basically the return values of some curl calls that I stored in variables:

enter image description here

CodePudding user response:

jq -r '.[]' will transform your array to a stream with one number per line -- which is the format that standard UNIX tools expect to work with.

Once we have the numbers in a sorted form, we can use comm to compare the two streams. -3 tells comm to ignore contents present in both streams, and -2 tells it to ignore content present only in the second stream, so comm -23 prints only files unique to the first stream.

Using readarray (added in bash 4.0) then lets us read that content into an array, which we can iterate over in our for loop.

#!/usr/bin/env bash
slot_ids='[1,2,3,4,5]'
pr_ids='[3,4]'

readarray -t filtered_slot_ids <(
  comm -23 \
    <(jq -r '.[]' <<<"$slot_ids" | sort) \
    <(jq -r '.[]' <<<"$pr_ids" | sort))

for i in "${filtered_slot_ids[@]}"; do
  az webapp deployment slot delete -g group --name webapp --slot "pr-$i"
done
  •  Tags:  
  • bash
  • Related