yamlyq

How to update the values for all keys matching a given pattern using yq?


I have a yaml file looks like

part1:
  name: tom
  some_field: true
part2:
  name: jerry
  other_field: true

and I would like to change the value of all keys that end with field into false, that is, converting the previous YAML file into

part1:
  name: tom
  some_field: false
part2:
  name: jerry
  other_field: false

Not sure how to do that yq


Solution

  • Which implementation of yq are you targetting?

    With mikefarah/yq (>= 4.0), you can use a globbing asterisk (and drop e / eval since v4.18):

    yq e '.[].*field = false' file.yaml
    

    With kislyuk/yq (jq >= 1.6), use endswith to select, and with_entries to update:

    yq -y '.[] |= with_entries(select(.key | endswith("field")).value = false)' file.yaml
    

    Both output:

    part1:
      name: tom
      some_field: false
    part2:
      name: jerry
      other_field: false
    

    Instead of unconditionally assigning false, you also might want to consider flipping a boolean by changing = false to |= not.