Home > Enterprise >  Yaml - how to replace key value using sed?
Yaml - how to replace key value using sed?

Time:01-04

I have a yaml config, and I want to replace one of the fields with a new value?

Here is an example of the yaml config:

application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "foobar"

I want to replace "foobar" under the build_image_tag field and replace it with a different value like "latest". How do I do this?

I tried the following:

sed '/^parameters:/{n;s/build_image_tag:.*/build_image_tag: "latest"/;}' exec.yml

But that didn't seem to work. The yaml config should look like this:

application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "latest"

CodePudding user response:

With go yq or python yq, the proper tools:

$ yq -i '.parameters.build_image_tag="latest"' file.yaml
application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "latest"
  • yq use the same syntax than jq for JSON
  • the -i is the same as sed -i: replace on the fly
  • Related