yq/operators/path.md

101 lines
1.4 KiB
Markdown
Raw Normal View History

2021-10-30 03:14:39 +00:00
# Path
The path operator can be used to get the traversal paths of matching nodes in an expression. The path is returned as an array, which if traversed in order will lead to the matching node.
You can get the key/index of matching nodes by using the `path` operator to return the path array then piping that through `.[-1]` to get the last element of that array, the key.
2022-02-06 03:41:27 +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-10-30 03:14:39 +00:00
## Map path
Given a sample.yml file of:
```yaml
a:
b: cat
```
then
```bash
2022-01-28 01:45:43 +00:00
yq '.a.b | path' sample.yml
2021-10-30 03:14:39 +00:00
```
will output
```yaml
- a
- b
```
## Get map key
Given a sample.yml file of:
```yaml
a:
b: cat
```
then
```bash
2022-01-28 01:45:43 +00:00
yq '.a.b | path | .[-1]' sample.yml
2021-10-30 03:14:39 +00:00
```
will output
```yaml
b
```
## Array path
Given a sample.yml file of:
```yaml
a:
- cat
- dog
```
then
```bash
2022-01-28 01:45:43 +00:00
yq '.a.[] | select(. == "dog") | path' sample.yml
2021-10-30 03:14:39 +00:00
```
will output
```yaml
- a
- 1
```
## Get array index
Given a sample.yml file of:
```yaml
a:
- cat
- dog
```
then
```bash
2022-01-28 01:45:43 +00:00
yq '.a.[] | select(. == "dog") | path | .[-1]' sample.yml
2021-10-30 03:14:39 +00:00
```
will output
```yaml
1
```
## Print path and value
Given a sample.yml file of:
```yaml
a:
- cat
- dog
- frog
```
then
```bash
2022-01-28 01:45:43 +00:00
yq '.a[] | select(. == "*og") | [{"path":path, "value":.}]' sample.yml
2021-10-30 03:14:39 +00:00
```
will output
```yaml
- path:
- a
- 1
value: dog
- path:
- a
- 2
value: frog
```
2021-11-03 04:00:28 +00:00