用 bash 替换 yml 中一行的值 [英] Replace value of a line in a yml with bash

查看:16
本文介绍了用 bash 替换 yml 中一行的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"

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

I would like to have a bash script to replace the nginx for an argument with bash script.

./script apache

nginx 替换为 apache

推荐答案

可以这样使用:sed -r 's/^(s*)(images*:s*nginxs*$)/1image: apache/'文件

示例运行:

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

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

To persist the changes into the file you can use in-place option like this:

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

<小时>

如果你想把它放在一个脚本里,你可以把 sed 命令放在一个脚本里,然后用 $1 代替执行它.


If you want it inside a script you can just put the sed command inside a script and execute it with $1 in sustitution.

$ vim script.sh 
$ cat script.sh 
sed -ri 's/^(s*)(images*:s*nginxs*$)/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"
$

这篇关于用 bash 替换 yml 中一行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆