In yq, how can I get multiple nodes by key names and return the key names with their content?

183 views Asked by At

I have the following data.

_format_version: "1.1"
_info:
  select_tags:
    - test
_workspace: test
plugins:
  - blah: abc
routes: 
  - blah: def
services: 
  - blah: ghi

I need to extract the keys that start with underscore and return the keys with their content. Example:

_format_version: "1.1"
_info:
  select_tags:
    - test
_workspace: test

All attempts fail to return the keys with the content.

$ yq '._format_version,._info,._workspace' test.yml
1.1
select_tags:
  - test
test

I have tried in(), select() and match() but can't get any of them to work.

$ yq eval 'select(keys[] | in(["_format_version", "_info", "_workspace"]))' test.yml 
Error: 1:17: invalid input text "in([\"_format_ver..."

I tried del() to delete all non-matching keys but I cannot get | not to work. Using not still deleted _info.

$ yq 'del(._info | not)' test.yml
_format_version: "1.1"
_workspace: test
plugins:
  - blah: abc
routes:
  - blah: def
services:
  - blah: ghi

I am running yq on Mac OSX.

$ yq --version
yq (https://github.com/mikefarah/yq/) version v4.35.2
1

There are 1 answers

1
pmf On

With ._*, you can access all keys that start with an underscore. Get each key, collect them into an array […], and use the pick function to filter your input map by them.

yq 'pick([._* | key])' file.yaml
_format_version: "1.1"
_info:
  select_tags:
    - test
_workspace: test