'using yq to Increment value if field exists

I have the following yaml file:

name: myapp
app1:
  version: 1.2
  replicas: 1
app2:
  version: 2.3
  replicas: 1
app3:
  version: 4.0
app4:
  version: 2.4

I'd like to use yq to increment the values of each replicas field so it results in:

name: myapp
app1:
  version: 1.2
  replicas: 2
app2:
  version: 2.3
  replicas: 2
app3:
  version: 4.0
app4:
  version: 2.4

Any ideas ?



Solution 1:[1]

Use select with has to check if the field exists, and += to update it:

Using mikefarah/yq:

yq '(.[] | select(has("replicas")).replicas) += 1'

Using kislyuk/yq:

yq -y '(.[] | select(has("replicas")?).replicas) += 1'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pmf