Display keys in yaml-files that contain property

39 Views Asked by At

Given the following yaml file:

service1:
  host:  s1
  port:  27000
service2:
  host:  s2
  port:  27001
service3:
  host:  s3
service4:
  host:  s4
  port:  27004

I want to list all keys, whose objects contain a "port" field.

Expected output:

- service1
- service2
- service4

Using the following command returns all keys, including "service3":

./yq 'keys | .[] comments=""' file.yml

However, since service3 does not have a port, it should be omitted. I tried using filter, has, map, select, ..., but couldn't achieve what I wanted.

1

There are 1 best solutions below

0
pmf On BEST ANSWER

Using the following command:

./yq 'keys | .[] comments=""' file.yml

...returns all keys, including "service3".

This does not test for any existence of "port".

You could map the items to their key, and select only those having an own key given using has:

yq 'map(select(has("port")) | key)' file.yml 
- service1
- service2
- service4

Tested with mikefarah/yq version v4.34.2