y
y
yq
Search…
Reduce
Reduce is a powerful way to process a collection of data into a new form.
1
<exp> as lt;name> ireduce (<init>; <block>)
Copied!
e.g.
1
.[] as $item ireduce (0; . + $item)
Copied!
On the LHS we are configuring the collection of items that will be reduced <exp> as well as what each element will be called lt;name>. Note that the array has been splatted into its individual elements.
On the RHS there is <init>, the starting value of the accumulator and <block>, the expression that will update the accumulator for each element in the collection. Note that within the block expression, . will evaluate to the current value of the accumulator.

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, where 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 jq like prefix version of reduce is ever added.

Sum numbers

Given a sample.yml file of:
1
- 10
2
- 2
3
- 5
4
- 3
Copied!
then
1
yq eval '.[] as $item ireduce (0; . + $item)' sample.yml
Copied!
will output
1
20
Copied!

Merge all yaml files together

Given a sample.yml file of:
1
a: cat
Copied!
And another sample another.yml file of:
1
b: dog
Copied!
then
1
yq eval-all '. as $item ireduce ({}; . * $item )' sample.yml another.yml
Copied!
will output
1
a: cat
2
b: dog
Copied!

Convert an array to an object

Given a sample.yml file of:
1
- name: Cathy
2
has: apples
3
- name: Bob
4
has: bananas
Copied!
then
1
yq eval '.[] as $item ireduce ({}; .[$item | .name] = ($item | .has) )' sample.yml
Copied!
will output
1
Cathy: apples
2
Bob: bananas
Copied!