Search code examples
yamlyq

How to delete object and list elements whose name or key end with string using yq


Given a yaml file I would like to remove all objects whose key ends with "Test" and also all array values that end with "Test" independent of the depth (recursively)

#Input

project: A project name
targets:
  targetA:
    name: "target A"
    path: "/some/path"
    sources:
      - "Source A"
      - "Source B"
      - "Source with Test"

  targetATest:
    name: "target A test"
    path: "/some/path"
    sources:
      - "Source A"
      - "Source B"
      

#Output

project: A project name
targets:
  targetA:
    name: "target A"
    path: "/some/path"
    sources:
      - "Source A"
      - "Source B"
      

Solution

  • I have tried a lot of variations of select with key like yq -i 'del(.. | select(tag == "!!map") | select(key | tag == "!!str"))' and test("") but with no success

    A straightforward solution using mikefarah/yq and your failed approach would be to separately test both your criteria:

    del(.. | select(
      (tag == "!!str" and test("Test$")) or
      (key | select(tag == "!!str") | test("Test$"))
    ))
    
    project: A project name
    targets:
      targetA:
        name: "target A"
        path: "/some/path"
        sources:
          - "Source A"
          - "Source B"