yq/operators/group-by.md
2022-02-06 14:41:27 +11:00

806 B

Group By

This is used to group items in an array by an expression.

{% hint style="warning" %} Note that versions prior to 4.18 require the 'eval/e' command to be specified.

yq e <exp> <file> {% endhint %}

Group by field

Given a sample.yml file of:

- foo: 1
  bar: 10
- foo: 3
  bar: 100
- foo: 1
  bar: 1

then

yq 'group_by(.foo)' sample.yml

will output

- - foo: 1
    bar: 10
  - foo: 1
    bar: 1
- - foo: 3
    bar: 100

Group by field, with nuls

Given a sample.yml file of:

- cat: dog
- foo: 1
  bar: 10
- foo: 3
  bar: 100
- no: foo for you
- foo: 1
  bar: 1

then

yq 'group_by(.foo)' sample.yml

will output

- - cat: dog
  - no: foo for you
- - foo: 1
    bar: 10
  - foo: 1
    bar: 1
- - foo: 3
    bar: 100