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.
Use setpath to set a value to the path array returned by path, and similarly delpaths for an array of path arrays.
Map path
Given a sample.yml file of:
a:
  b: catthen
yq '.a.b | path' sample.ymlwill output
- a
- bGet map key
Given a sample.yml file of:
a:
  b: catthen
yq '.a.b | path | .[-1]' sample.ymlwill output
bArray path
Given a sample.yml file of:
a:
  - cat
  - dogthen
yq '.a.[] | select(. == "dog") | path' sample.ymlwill output
- a
- 1Get array index
Given a sample.yml file of:
a:
  - cat
  - dogthen
yq '.a.[] | select(. == "dog") | path | .[-1]' sample.ymlwill output
1Print path and value
Given a sample.yml file of:
a:
  - cat
  - dog
  - frogthen
yq '.a[] | select(. == "*og") | [{"path":path, "value":.}]' sample.ymlwill output
- path:
    - a
    - 1
  value: dog
- path:
    - a
    - 2
  value: frogSet path
Given a sample.yml file of:
a:
  b: catthen
yq 'setpath(["a", "b"]; "things")' sample.ymlwill output
a:
  b: thingsSet on empty document
Running
yq --null-input 'setpath(["a", "b"]; "things")'will output
a:
  b: thingsSet path to prune deep paths
Like pick but recursive. This uses ireduce to deeply set the selected paths into an empty object.
Given a sample.yml file of:
parentA: bob
parentB:
  child1: i am child1
  child2: i am child2
parentC:
  child1: me child1
  child2: me child2then
yq '(.parentB.child2, .parentC.child1) as $i
  ireduce({}; setpath($i | path; $i))' sample.ymlwill output
parentB:
  child2: i am child2
parentC:
  child1: me child1Set array path
Given a sample.yml file of:
a:
  - cat
  - frogthen
yq 'setpath(["a", 0]; "things")' sample.ymlwill output
a:
  - things
  - frogSet array path empty
Running
yq --null-input 'setpath(["a", 0]; "things")'will output
a:
  - thingsDelete path
Notice delpaths takes an array of paths.
Given a sample.yml file of:
a:
  b: cat
  c: dog
  d: frogthen
yq 'delpaths([["a", "c"], ["a", "d"]])' sample.ymlwill output
a:
  b: catDelete array path
Given a sample.yml file of:
a:
  - cat
  - frogthen
yq 'delpaths([["a", 0]])' sample.ymlwill output
a:
  - frogDelete - wrong parameter
delpaths does not work with a single path array
Given a sample.yml file of:
a:
  - cat
  - frogthen
yq 'delpaths(["a", 0])' sample.ymlwill output
Error: DELPATHS: expected entry [0] to be a sequence, but its a !!str. Note that delpaths takes an array of path arrays, e.g. [["a", "b"]]Last updated
Was this helpful?