mirror of
https://github.com/taigrr/yq
synced 2025-01-18 04:53:17 -08:00
44 lines
1002 B
Markdown
44 lines
1002 B
Markdown
Reduce is a powerful way to process a collection of data into a new form.
|
|
|
|
## yq vs jq syntax
|
|
Reduce syntax in `yq` is a little different from `jq` - as `yq` (currently) isn't as sophisticated as `jq` and its only supports infix notation (e.g. a + b, the operator is in the middle of the two parameters) - where as `jq` uses a mix of infix notation with _prefix_ notation (e.g. `reduce a b` is like writing `+ a b`).
|
|
|
|
To that end, the reduce operator is called `ireduce` for backwards compatability if a prefix version of `reduce` is ever added.
|
|
|
|
|
|
## Sum numbers
|
|
Given a sample.yml file of:
|
|
```yaml
|
|
- 10
|
|
- 2
|
|
- 5
|
|
- 3
|
|
```
|
|
then
|
|
```bash
|
|
yq eval '.[] as $item ireduce (0; . + $item)' sample.yml
|
|
```
|
|
will output
|
|
```yaml
|
|
20
|
|
```
|
|
|
|
## Convert an array to an object
|
|
Given a sample.yml file of:
|
|
```yaml
|
|
- name: Cathy
|
|
has: apples
|
|
- name: Bob
|
|
has: bananas
|
|
```
|
|
then
|
|
```bash
|
|
yq eval '.[] as $item ireduce ({}; .[$item | .name] = ($item | .has) )' sample.yml
|
|
```
|
|
will output
|
|
```yaml
|
|
Cathy: apples
|
|
Bob: bananas
|
|
```
|
|
|