yq/pkg/yqlib/doc/operators/variable-operators.md

105 lines
1.9 KiB
Markdown
Raw Normal View History

2021-11-03 04:00:58 +00:00
# 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.
2022-02-06 03:39:46 +00:00
{% hint style="warning" %}
Note that versions prior to 4.18 require the 'eval/e' command to be specified. 
`yq e <exp> <file>`
{% endhint %}
2021-11-03 04:00:58 +00:00
## Single value variable
Given a sample.yml file of:
```yaml
a: cat
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.a as $foo | $foo' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
cat
```
## Multi value variable
Given a sample.yml file of:
```yaml
- cat
- dog
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.[] as $foo | $foo' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
cat
dog
```
## Using variables as a lookup
Example taken from [jq](https://stedolan.github.io/jq/manual/#Variable/SymbolicBindingOperator:...as$identifier|...)
Given a sample.yml file of:
```yaml
"posts":
2022-05-24 08:18:27 +00:00
- "title": First post
2021-11-03 04:00:58 +00:00
"author": anon
- "title": A well-written article
"author": person1
"realnames":
"anon": Anonymous Coward
"person1": Person McPherson
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.realnames as $names | .posts[] | {"title":.title, "author": $names[.author]}' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
2022-05-24 08:18:27 +00:00
title: First post
2021-11-03 04:00:58 +00:00
author: Anonymous Coward
title: A well-written article
author: Person McPherson
```
## Using variables to swap values
Given a sample.yml file of:
```yaml
a: a_value
b: b_value
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.a as $x | .b as $y | .b = $x | .a = $y' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
a: b_value
b: a_value
```
## Use ref to reference a path repeatedly
Note: You may find the `with` operator more useful.
Given a sample.yml file of:
```yaml
a:
b: thing
c: something
```
then
```bash
2022-01-27 06:21:10 +00:00
yq '.a.b ref $x | $x = "new" | $x style="double"' sample.yml
2021-11-03 04:00:58 +00:00
```
will output
```yaml
a:
b: "new"
c: something
```