Search code examples
yq

How to search if a particular word exists in keys in yml file using yq


I just picked up on the yq tool recently and been struggling to find a way to check if a particular word exists in the keys of a yml file.

Say the yml file is as follows,

key1:
  value1
key_with_test:
  value2
key3:
  value3

In this case, I would like to search if they is a key with the word "test".

I have tried the following commands,

yq eval "keys | has("test")"
yq eval "keys | select(. == "*test")"

But don't seem to be working as expected. Expected being a bool if exists and maybe if possible how to access that henceforth.


Solution

  • yq uses a different syntax than jq to get elements from the array. In the latter you could just do .arr[], but former expects .arr | .[]. So putting it together

    yq e 'keys | .[] | select(. == "*test")' yaml
    

    Also note that has does not support a regex/glob search but only for exact match string.

    Note: Since 4.18.1, yq's eval/e command is the default command and no longer needs to be specified.