【问题标题】:Replace value of a line in a yml with bash用 bash 替换 yml 中一行的值
【发布时间】:2016-09-14 10:16:16
【问题描述】:
web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"

我想要一个 bash 脚本来用 bash 脚本替换 nginx 的参数。

./script apache

nginx 替换为apache

【问题讨论】:

  • 由于您似乎想要覆盖 docker-compose 文件中的值,您可能想查看我的 docker compose wrapper program 允许可以被环境变量覆盖的默认值(例如区分测试和生产系统)。因为它支持 YAML 1.2,所以它还让您无需引用那些可以被 compose 的默认 YAML 1.1 解析器解释为六十进制的"3030:3000" 端口映射

标签: bash shell yaml


【解决方案1】:

您可以按如下方式创建您的 script.sh:

#!/bin/bash
# $1 image value you want to replace
# $2 is the file you want to edit
sed -i "" "/^\([[:space:]]*image: \).*/s//\1$1/" $2

然后运行: ./script.sh apache 文件名.yaml

【讨论】:

  • 空引号""是必要的吗?他们是做什么的?
  • 正确答案:sed -i "/^\([[:space:]]*image: \).*/s//\1$1/" $2,去掉空引号否则会报no file or directory错误!
  • 要使其在 Linux 和 OSX 中都能正常工作,请在 -i 旁边添加 .bak,例如sed if.bak ...。然后当然可以删除 .bak 文件。
【解决方案2】:

由于这显然是一个 docker-compose 文件,您可能想尝试一下

 image: ${webserver_image}

然后设置:

 webserver_image=[nginx | apache]

在启动之前。我相信这应该会给你一个很好的插值。

【讨论】:

    【解决方案3】:

    脚本:

    #!/bin/bash
    sed -i.bak "s/\bnginx\b/$1/g" file
    # \b matches for word boundary
    # -i changes the file in-place
    # -i.bak produces a backup with .bak extension
    

    现在您可以使用./script apachenginx 替换为 apache

    【讨论】:

      【解决方案4】:

      你可以使用这个:sed -r 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file

      示例运行:

      $ cat file
      web:
        image: nginx
        volumes:
          - "./app:/src/app"
        ports:
          - "3030:3000"
          - "35729:35729"
      $ sed -r 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file
      web:
        image: apache
        volumes:
          - "./app:/src/app"
        ports:
          - "3030:3000"
          - "35729:35729"
      

      要将更改保存到文件中,您可以使用这样的就地选项:

      $ sed -ri 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file
      

      如果您想在脚本中使用它,您可以将sed 命令放入脚本中,然后用$1 代替执行它。

      $ vim script.sh 
      $ cat script.sh 
      sed -ri 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: '"$1"'/' file
      $ chmod 755 script.sh 
      $ cat file 
      web:
        image: nginx
        volumes:
          - "./app:/src/app"
        ports:
          - "3030:3000"
          - "35729:35729"
      $ ./script.sh apache
      $ cat file 
      web:
        image: apache
        volumes:
          - "./app:/src/app"
        ports:
          - "3030:3000"
          - "35729:35729"
      $
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-10
        • 2018-09-14
        • 2017-01-22
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 2014-02-02
        相关资源
        最近更新 更多