Home > Software design >  JQ usage to filter content
JQ usage to filter content

Time:12-04


I want to filter and get the results of each index that

it's name starts with "abc" and the state is "DISABLED".

My file looks like this:

➜  ~ cat test.json | head
{
  "Rules": [
    {
      "Name": "abcd",
      "Arn": "arn:aws:events:eu-west-2:XXXXXX:rule/abcd",
      "State": "ENABLED",
      "ScheduleExpression": "rate(6 hours)",
      "EventBusName": "default"
    },
    {
      "Name": "abcxxx",
      "Arn": "arn:aws:events:eu-west-2:XXXXXX:rule/abcxxx",
      "State": "DISABLED",
      "ScheduleExpression": "rate(12 hours)",
      "EventBusName": "default"
    }
  ]
}


I tried to use this command:

cat test.json | jq -r '.[] | .[] |  select(.Name | startswith("abc"))'

And it's giving me whatever starts with "abc" which is good but I want it to be also
.State == "DISABLED" and I want the output to be regular and not JSON.
(I need to get the names of whatever starts with abc and it's state is DISABLED into a file)

Thank youuuu!

CodePudding user response:

Adding a second condition with the and operator will allow you to filter with your 2 conditions:

cat test.json | jq -r '.[] | .[] |  select((.Name | startswith("abc")) and .State == "DISABLED") 

Then to extract Name field

cat test.json | jq -r '.[] | .[] |  select((.Name | startswith("abc")) and .State == "DISABLED") | .Name'
  • Related