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.
Given a sample.yml file of:
a:b: cat
then
yq eval '.a.b | path' sample.yml
will output
- a- b
Given a sample.yml file of:
a:b: cat
then
yq eval '.a.b | path | .[-1]' sample.yml
will output
b
Given a sample.yml file of:
a:- cat- dog
then
yq eval '.a.[] | select(. == "dog") | path' sample.yml
will output
- a- 1
Given a sample.yml file of:
a:- cat- dog
then
yq eval '.a.[] | select(. == "dog") | path | .[-1]' sample.yml
will output
1
Given a sample.yml file of:
a:- cat- dog- frog
then
yq eval '.a.[] | select(. == "*og") | [{"path":path, "value":.}]' sample.yml
will output
- path:- a- 1value: dog- path:- a- 2value: frog