yq/operators/group-by.md

63 lines
806 B
Markdown
Raw Normal View History

2021-10-30 03:43:45 +00:00
# Group By
This is used to group items in an array by an expression.
2022-02-06 03:41:27 +00:00
{% hint style="warning" %}
Note that versions prior to 4.18 require the 'eval/e' command to be specified. 
`yq e <exp> <file>`
{% endhint %}
2021-10-30 03:43:45 +00:00
## Group by field
Given a sample.yml file of:
```yaml
- foo: 1
bar: 10
- foo: 3
bar: 100
- foo: 1
bar: 1
```
then
```bash
2022-01-28 01:45:43 +00:00
yq 'group_by(.foo)' sample.yml
2021-10-30 03:43:45 +00:00
```
will output
```yaml
- - foo: 1
bar: 10
- foo: 1
bar: 1
- - foo: 3
bar: 100
```
## Group by field, with nuls
Given a sample.yml file of:
```yaml
- cat: dog
- foo: 1
bar: 10
- foo: 3
bar: 100
- no: foo for you
- foo: 1
bar: 1
```
then
```bash
2022-01-28 01:45:43 +00:00
yq 'group_by(.foo)' sample.yml
2021-10-30 03:43:45 +00:00
```
will output
```yaml
- - cat: dog
- no: foo for you
- - foo: 1
bar: 10
- foo: 1
bar: 1
- - foo: 3
bar: 100
```