Substitue values in jq from a txt file

67 Views Asked by At

I'm executing jq like this:

jq '.backups[] | select(.resource_name == "resource_name") | {BackupTime: .updated_at, DiskName: .resource_name}' js.json | head -4

Is there a way to substitute the .resource_name field with the strings in a text file and execute a jq for each line of substitution from the text file?

For example, I have list.txt file with the below contents:

apple
mango
grapes

I want the jq command to be substituted as below:

jq '.backups[] | select(.resource_name == "**apple**") | {BackupTime: .updated_at, DiskName: .resource_name}' js.json | head -4
2

There are 2 best solutions below

0
potong On

This might work for you (GNU paste and sed or parallel):

cat <<\! >command.txt
jq '.backups[] | select(.resource_name == "resource_name") | {BackupTime: .updated_at, DiskName: .resource_name}' js.json
!

cat <<\! >list.txt
apple
mango
grape
!

sed -n 'r command.tx' list.txt | paste - list.txt | sed -E 's/".*"(.*)\t(.*)/"**\2**"\1/e'

Put the jq command in a text file

Put the list in a text file.

Apply the piped sed/paste/sed invocations.

The first sed invocation, creates a file of commands the length of the list.

The invocation of paste, appends the list separated by a tab.

The second invocation of sed, uses pattern matching to substitute then evalute the resulting line.

Another solution would to be to use GNU parallel:

parallel -k jq '.backups[] | select(.resource_name == "**{}**") | {BackupTime: .updated_at, DiskName: .resource_name}' js.json :::: list.txt
0
tripleee On

You mean like this?

while read -r resource; do
    jq --arg resource "$resource" '.backups[] |
        select(.resource_name == $rname) |
        {BackupTime: .updated_at, DiskName: .resource_name}' js.json |
    head -4
done <list.txt