Saturday, January 27, 2024

[SOLVED] Modify specific line in a yaml file using bash

Issue

I am trying to make sed to modify a content of yaml file which is as follows:

image-1:
    PrName: client Image
    number: client-image-1
    path: /home/user/
    name: client-image
    tag: 0.0.1-5

image-2:
    PrName: Server Image
    number: Server-image-1
    path: /home/user/
    name: server-image
    tag: 1.0.1-3

I want to have sed function to modify the content of yaml file. It modifies the tag of image-2 with specific value $NEW_TAG which is given as env variable.

I started with but I don't think it'd help "sed -i 's#tag:*?#$NEW_TAG?#' file.yaml"


Solution

Use a proper yaml parser like yq:

$ NEW_TAG=1.0.2 yq e --inplace ".image-2.tag|=strenv(NEW_TAG)" file.yaml
$ cat file.yaml
image-1:
  PrName: client Image
  number: client-image-1
  path: /home/user/
  name: client-image
  tag: 0.0.1-5
image-2:
  PrName: Server Image
  number: Server-image-1
  path: /home/user/
  name: server-image
  tag: 1.0.2


Answered By - Paolo
Answer Checked By - Katrina (WPSolving Volunteer)