unixsedcommand-lineyamlstring-parsing

Yaml - how to replace key value using sed?


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"

Solution

  • 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"