yq/pkg/yqlib/doc/Assign.md
Mike Farah f7f8bed955 wip
2020-12-27 09:55:21 +11:00

2.4 KiB

This operator is used to update node values. It can be used in either the:

plain form: =

Which will assign the LHS node values to the RHS node values. The RHS expression is run against the matching nodes in the pipeline.

relative form: |=

This will do a similar thing to the plain form, however, the RHS expression is run against the LHS nodes. This is useful for updating values based on old values, e.g. increment.

Create yaml file

Running

yq eval --null-input '.a.b = "cat" | .x = "frog"'

will output

a:
  b: cat
x: frog

Update node to be the child value

Given a sample.yml file of:

a: {b: {g: foof}}
'': null

then

yq eval '.a |= .b' sample.yml

will output

a: {g: foof}
'': null

Update node to be the sibling value

Given a sample.yml file of:

a: {b: child}
b: sibling
'': null

then

yq eval '.a = .b' sample.yml

will output

a: sibling
b: sibling
'': null

Updated multiple paths

Given a sample.yml file of:

a: fieldA
b: fieldB
c: fieldC
'': null

then

yq eval '(.a, .c) |= "potatoe"' sample.yml

will output

a: potatoe
b: fieldB
c: potatoe
'': null

Update string value

Given a sample.yml file of:

a: {b: apple}
'': null

then

yq eval '.a.b = "frog"' sample.yml

will output

a: {b: frog}
'': null

Update string value via |=

Note there is no difference between = and |= when the RHS is a scalar

Given a sample.yml file of:

a: {b: apple}
'': null

then

yq eval '.a.b |= "frog"' sample.yml

will output

a: {b: frog}
'': null

Update selected results

Given a sample.yml file of:

a: {b: apple, c: cactus}
'': null

then

yq eval '(.a[] | select(. == "apple")) = "frog"' sample.yml

will output

a: {b: frog, c: cactus}
'': null

Update array values

Given a sample.yml file of:

- candy
- apple
- sandy

then

yq eval '(.[] | select(. == "*andy")) = "bogs"' sample.yml

will output

- bogs
- apple
- bogs

Update empty object

Given a sample.yml file of:

{}

then

yq eval '.a.b |= "bogs"' sample.yml

will output

{a: {b: bogs}}

Update empty object and array

Given a sample.yml file of:

{}

then

yq eval '.a.b.[0] |= "bogs"' sample.yml

will output

{a: {b: [bogs]}}