用bash替换yml中一行的值

Iva*_*tos 14 bash shell yaml

web:
  image: nginx
  volumes:
    - "./app:/src/app"
  ports:
    - "3030:3000"
    - "35729:35729"
Run Code Online (Sandbox Code Playgroud)

我想有一个bash脚本用bash脚本替换nginxfor参数.

./script apache
Run Code Online (Sandbox Code Playgroud)

将替换nginxapache

rit*_*t93 14

你可以用这个: 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"
Run Code Online (Sandbox Code Playgroud)

要将更改保留到文件中,您可以使用就地选项,如下所示:

$ sed -ri 's/^(\s*)(image\s*:\s*nginx\s*$)/\1image: apache/' file
Run Code Online (Sandbox Code Playgroud)

如果你想在脚本中使用它,你可以将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"
$
Run Code Online (Sandbox Code Playgroud)


rma*_*how 7

因为这显然是一个 docker-compose 文件,你可能想尝试

 image: ${webserver_image}
Run Code Online (Sandbox Code Playgroud)

然后设置:

 webserver_image=[nginx | apache]
Run Code Online (Sandbox Code Playgroud)

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


flo*_*h2o 7

您可以按如下方式创建 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
Run Code Online (Sandbox Code Playgroud)

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

  • 正确答案:`sed -i "/^\([[:space:]]*image: \).*/s//\1$1/" $2` ,去掉空引号,否则会报错 no file或目录错误! (2认同)

Jah*_*hid 5

脚本:

#!/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
Run Code Online (Sandbox Code Playgroud)

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