y
y
yq
Search…
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.

Map path

Given a sample.yml file of:
1
a:
2
b: cat
Copied!
then
1
yq eval '.a.b | path' sample.yml
Copied!
will output
1
- a
2
- b
Copied!

Get map key

Given a sample.yml file of:
1
a:
2
b: cat
Copied!
then
1
yq eval '.a.b | path | .[-1]' sample.yml
Copied!
will output
1
b
Copied!

Array path

Given a sample.yml file of:
1
a:
2
- cat
3
- dog
Copied!
then
1
yq eval '.a.[] | select(. == "dog") | path' sample.yml
Copied!
will output
1
- a
2
- 1
Copied!

Get array index

Given a sample.yml file of:
1
a:
2
- cat
3
- dog
Copied!
then
1
yq eval '.a.[] | select(. == "dog") | path | .[-1]' sample.yml
Copied!
will output
1
1
Copied!

Print path and value

Given a sample.yml file of:
1
a:
2
- cat
3
- dog
4
- frog
Copied!
then
1
yq eval '.a[] | select(. == "*og") | [{"path":path, "value":.}]' sample.yml
Copied!
will output
1
- path:
2
- a
3
- 1
4
value: dog
5
- path:
6
- a
7
- 2
8
value: frog
Copied!
Last modified 1mo ago