用 bash 替换 yml 中一行的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37290935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:38:33  来源:igfitidea点击:

Replace value of a line in a yml with bash

bashshellyaml

提问by Ivan Santos

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

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

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

./script apache

Will replace nginxfor apache

将替换nginxapache

回答by riteshtch

You can use this: sed -r 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file

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

Sample run:

示例运行:

$ cat file
web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"
$ sed -r 's/^(\s*)(image\s*:\s*nginx\s*$)/image: 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*)(image\s*:\s*nginx\s*$)/image: apache/' file


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

如果你想把它放在一个脚本中,你可以把sed命令放在一个脚本中并替换它来执行它$1

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

回答by Jahid

script:

脚本:

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

Now you can do ./script apacheto replace nginxwith apache.

现在你可以用apache./script apache替换nginx了。

回答by flowinh2o

You could create your script.sh as follows:

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

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

And then run: ./script.sh apache filename.yaml

然后运行:./script.sh apache filename.yaml

回答by rmalchow

since this is apparently a docker-compose file, you might want to try

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

 image: ${webserver_image}

and then set:

然后设置:

 webserver_image=[nginx | apache]

before launching. i believe this should give you a nice interpolation.

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