Yaml YQ - How do you use [], but still print out the keys that the iterator refers to

Viewed 62

I have a yaml file that looks like this:

---
component1:
  tests:
    - name: test1
      type: manual
    - name: test2
      type: automated
    - name: test3
      type: manual
    - name: test4
      type: automated
    - name: test5
      type: manual
    - name: test6
      type: automated
component2:
  tests:
    - name: test1
      type: manual
    - name: test2
      type: automated
    - name: test3
      type: manual
    - name: test4
      type: automated
    - name: test5
      type: manual
    - name: test6
      type: automated

I am trying to list only the automated tests, but keep the information about which component the tests are in.

I would like the output to be similar to this:

component1:
  tests:
    - name: test2
      type: automated
    - name: test4
      type: automated
    - name: test6
      type: automated
component2:
  tests:
    - name: test2
      type: automated
    - name: test4
      type: automated
    - name: test6
      type: automated

But I would also take any answer that allowed me to group the automated tests by component.

I have tried yq e '.[].tests | map(select(.type == "automated"))' file.yaml -P, but that just gives me the following output and the component information is lost and I just get the following output:

- name: test2
  type: automated
- name: test4
  type: automated
- name: test6
  type: automated
- name: test2
  type: automated
- name: test4
  type: automated
- name: test6
  type: automated
1 Answers

Assuming you are using mikefarah/yq, you can use the update select operator with |= to update the results back to the tests list

yq e '.[].tests |= map(select(.type == "automated"))' file.yaml -P

Note that, if you are using yq version above 4.18.1, the eval action e is the default one and can be skipped altogether.

Related