y
y
yq
Search…
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.
Note that versions prior to 4.18 require the 'eval/e' command to be specified.
yq e <exp> <file>

Single value variable

Given a sample.yml file of:
1
a: cat
Copied!
then
1
yq '.a as $foo | $foo' sample.yml
Copied!
will output
1
cat
Copied!

Multi value variable

Given a sample.yml file of:
1
- cat
2
- dog
Copied!
then
1
yq '.[] as $foo | $foo' sample.yml
Copied!
will output
1
cat
2
dog
Copied!

Using variables as a lookup

Example taken from jq
Given a sample.yml file of:
1
"posts":
2
- "title": First post
3
"author": anon
4
- "title": A well-written article
5
"author": person1
6
"realnames":
7
"anon": Anonymous Coward
8
"person1": Person McPherson
Copied!
then
1
yq '.realnames as $names | .posts[] | {"title":.title, "author": $names[.author]}' sample.yml
Copied!
will output
1
title: First post
2
author: Anonymous Coward
3
title: A well-written article
4
author: Person McPherson
Copied!

Using variables to swap values

Given a sample.yml file of:
1
a: a_value
2
b: b_value
Copied!
then
1
yq '.a as $x | .b as $y | .b = $x | .a = $y' sample.yml
Copied!
will output
1
a: b_value
2
b: a_value
Copied!

Use ref to reference a path repeatedly

Note: You may find the with operator more useful.
Given a sample.yml file of:
1
a:
2
b: thing
3
c: something
Copied!
then
1
yq '.a.b ref $x | $x = "new" | $x style="double"' sample.yml
Copied!
will output
1
a:
2
b: "new"
3
c: something
Copied!
Last modified 1mo ago