Variable Operators
Like the jq equivalents, variables are sometimes required for the more complex expressions (or swapping values between fields).
Note that there is also an additional ref operator that holds a reference (instead of a copy) of the path, allowing you to make multiple changes to the same path.
Single value variable
Given a sample.yml file of:
a: catthen
yq '.a as $foo | $foo' sample.ymlwill output
catMulti value variable
Given a sample.yml file of:
- cat
- dogthen
yq '.[] as $foo | $foo' sample.ymlwill output
cat
dogUsing variables as a lookup
Example taken from jq
Given a sample.yml file of:
"posts":
- "title": First post
"author": anon
- "title": A well-written article
"author": person1
"realnames":
"anon": Anonymous Coward
"person1": Person McPhersonthen
yq '.realnames as $names | .posts[] | {"title":.title, "author": $names[.author]}' sample.ymlwill output
title: First post
author: Anonymous Coward
title: A well-written article
author: Person McPhersonUsing variables to swap values
Given a sample.yml file of:
a: a_value
b: b_valuethen
yq '.a as $x | .b as $y | .b = $x | .a = $y' sample.ymlwill output
a: b_value
b: a_valueUse ref to reference a path repeatedly
Note: You may find the with operator more useful.
Given a sample.yml file of:
a:
b: thing
c: somethingthen
yq '.a.b ref $x | $x = "new" | $x style="double"' sample.ymlwill output
a:
b: "new"
c: somethingLast updated
Was this helpful?