在 CLI 上更新 YAML 值

Update YAML value on CLI

我想更改基于 backend.image.tag

键的 yaml 文件值

我已经使用了 yq 之类的工具,但不幸的是,更新值时格式被破坏了。所以我想用 awk sed 等工具更新 yaml 文件的值。

给定的 yaml 文件:

frontend:
  # Some comments
  image:
    repository: frontend
    pullPolicy: IfNotPresent
    tag: "1.0.0"

# Some comments

backend:

  image:
    repository: backend
    pullPolicy: IfNotPresent
    tag: "1.3.1.beta-2cdfxq2"

预期的 yaml 文件:

frontend:
  # Some comments
  image:
    repository: frontend
    pullPolicy: IfNotPresent
    tag: "1.0.0"

# Some comments

backend:

  image:
    repository: backend
    pullPolicy: IfNotPresent
    tag: "1.3.2"

正如其他人所指出的,专用的 yaml 处理器(例如 jq)始终是首选,但以下可能是另一种选择:

awk '/^[[:alnum:]]+:$/ { label= } /^[[:space:]]+image:$/ { img=1 } /^[[:space:]]+tag:/ && img==1 && label=="backend:" { img=0;gsub("\".*\"","\"1.3.1\"",[=10=]);print;next }1' file

解释:

awk '/^[[:alnum:]]+:$/ { 
                          label=                                            # Search for tags anchored at the start of the line and track them by reading the result into the variable label.
                       } 
     /^[[:space:]]+image:$/ { 
                          img=1                                               # Search for image tags and if we find them, set a process flag img to 1
                       } 
     /^[[:space:]]+tag:/ && img==1 && label=="backend:" {                     # When label is backend, image process flag is 1 and current line is tag, process.
                          img=0;                                              # Reset the img flag
                          gsub("\".*\"","\"1.3.1\"",[=11=]);                      # Replace anything in between quotes with 1.3.1                      
                          print;                                              # Print the resulting line
                          next                                                # Skip to the next line
                        }1' file                                              # Print all un amended lines through 1