【问题标题】:sed command is not working to find and replace content in yaml file?sed 命令无法在 yaml 文件中查找和替换内容?
【发布时间】:2021-12-15 22:33:47
【问题描述】:

我在 yaml 文件 des.yaml 中有以下内容

simulator:
  enabled: false

我想通过如下方式启用模拟器:

simulator:
  enabled: true

使用 sed 命令

我尝试使用 sed 命令,但它无法正常工作:

sed -i 's|simulator\:\n  enabled\: false|simulator\:\n  enabled\:  true|' des.yaml

命令没有抛出任何错误。

请帮忙

【问题讨论】:

    标签: linux sed scripting


    【解决方案1】:

    这可能对你有用(GNU sed):

    sed -i '/simulator:/{n;/enabled:/s/false/true/}' file
    

    匹配simulator:,打印该行并获取下一行。

    匹配enabled:,将false 替换为true

    【讨论】:

      【解决方案2】:

      虽然sed之类的程序可以解决问题,但还是应该使用合适的工具,这里:https://github.com/mikefarah/yq/releases/

      yq eval '.simulator.enabled=true' des.yaml
      

      【讨论】:

        【解决方案3】:

        使用sed

        $ sed -i '/simulator/ {N;s/\(enabled: \).*/\1true/}' input_file
        

        如果找到匹配simulator,则移动到下一行,如果匹配enabled存在,则值将更改为true。

        输出

        simulator:
          enabled: true
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-07
          • 2018-10-01
          • 2012-12-29
          • 2017-08-23
          • 2017-09-12
          • 2010-12-20
          • 2012-02-14
          相关资源
          最近更新 更多