Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing regular expression from variable in jq

Tags:

jq

I'm trying to filter AWS ECR image list returned as JSON with jq and regular expressions.

Following command work as expected and return filtered list:

aws ecr list-images --registry-id 123456789012 --repository-name repo | jq '.imageIds | map(select(.imageTag)) | map(select(.imageTag | test("[a-z0-9]-[0-9]")))'

[
  {
    "imageTag": "bbe3d9-2",
    "imageDigest": "sha256:4c0e92098010fd26e07962eb6e9c7d23315bd8f53885a0651d06c2e2e051317d"
  },
  {
    "imageTag": "3c840a-1",
    "imageDigest": "sha256:9d05e04ccd18f2795121118bf0407b0636b9567c022908550c54e3c77534f8c1"
  },
  {
    "imageTag": "1c0d05-141",
    "imageDigest": "sha256:a62faabb9199bfc449f0e0a6d3cdc9be57b688a0890f43684d6d89abcf909ada"
  }
]

But when I try to pass regular expression as an argument to jq it return an empty array.

aws ecr list-images --registry-id 123456789012 --repository-name repo | jq --arg reg_exp "[a-z0-9]-[0-9]" '.imageIds | map(select(.imageTag)) | map(select(.imageTag | test("$reg_exp")))'

[]

I have tried multiple ways to pass that variable, but just can't get it work. Other relevant information may be that I'm using zsh on mac and my jq version is jq-1.5. Any help is appreciated.

like image 531
Niko Ruotsalainen Avatar asked Oct 20 '25 11:10

Niko Ruotsalainen


1 Answers

$reg_exp is a variable referring to your regular expression, "$reg_exp" is just a literal string. Remove the quotes. (and that extra map/select is redundant)

jq --arg reg_exp "[a-z0-9]-[0-9]" '.imageIds | map(select(.imageTag | test($reg_exp)))'
like image 73
Jeff Mercado Avatar answered Oct 23 '25 00:10

Jeff Mercado