【问题标题】:Update YAML value on CLI [closed]在 CLI 上更新 YAML 值 [关闭]
【发布时间】:2021-02-12 14:24:01
【问题描述】:

我想根据 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"

【问题讨论】:

  • 欢迎来到 SO,请以代码的形式添加您的努力,这是非常鼓励的,谢谢。
  • 使用 RegEx 引擎解析 YAML 与编写任何其他 YAML 实现一样复杂,因此我建议不要这样做。它可以做到,尽管有些人会告诉你它不能,因为他们将 RegEx 与常规语言混淆了。请注意,当您执行诸如匹配 ^\s*tag:\s+"([^"]*)"\s*$ 之类的简单操作时,它适用于您的示例,但也将匹配任何其他引用值与键 tag: 任何地方。您需要先定义您的先决条件(例如,任何地方都可以有任何其他 tag: 键),然后任何人都可以帮助您制作一个不实现所有 YAML 的可用于此的 RegEx。
  • 我投票结束这个问题,因为它与 unix.stackexchange.com/q/633696/133219 重复。只需将我在unix.stackexchange.com/a/633740/133219 发布的脚本称为awk -v tgt='backend.image.tag' -v val='"1.3.2"' -f tst.awk file

标签: bash awk sed yaml command-line-interface


【解决方案1】:

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

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

解释:

awk '/^[[:alnum:]]+:$/ { 
                          label=$1                                            # 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\"",$0);                      # 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多