yq/pkg/yqlib/doc/operators/path.md
2022-10-05 14:12:08 +11:00

2.0 KiB

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.

{% hint style="warning" %} Note that versions prior to 4.18 require the 'eval/e' command to be specified.

yq e <exp> <file> {% endhint %}

Map path

Given a sample.yml file of:

a:
  b: cat

then

yq '.a.b | path' sample.yml

will output

- a
- b

Get map key

Given a sample.yml file of:

a:
  b: cat

then

yq '.a.b | path | .[-1]' sample.yml

will output

b

Array path

Given a sample.yml file of:

a:
  - cat
  - dog

then

yq '.a.[] | select(. == "dog") | path' sample.yml

will output

- a
- 1

Get array index

Given a sample.yml file of:

a:
  - cat
  - dog

then

yq '.a.[] | select(. == "dog") | path | .[-1]' sample.yml

will output

1

Print path and value

Given a sample.yml file of:

a:
  - cat
  - dog
  - frog

then

yq '.a[] | select(. == "*og") | [{"path":path, "value":.}]' sample.yml

will output

- path:
    - a
    - 1
  value: dog
- path:
    - a
    - 2
  value: frog

Set path

Given a sample.yml file of:

a:
  b: cat

then

yq 'setpath(["a", "b"]; "things")' sample.yml

will output

a:
  b: things

Set on empty document

Running

yq --null-input 'setpath(["a", "b"]; "things")'

will output

a:
  b: things

Set array path

Given a sample.yml file of:

a:
  - cat
  - frog

then

yq 'setpath(["a", 0]; "things")' sample.yml

will output

a:
  - things
  - frog

Set array path empty

Running

yq --null-input 'setpath(["a", 0]; "things")'

will output

a:
  - things