1

我正在使用 shelljs 执行 shell 命令来查找和替换配置文件中的内容。我的配置是像下面这样的文件内容,我想通过我的诊所名称查找所有字符串“”(这是我从客户端传递的参数,例如:var ClinicName = req.body.clinicName;)

version: '3.2'
services:
  # core backend service
  core-backend:
    image: "vany/multi-tenant-core:latest"
    deploy:
      replicas: 1
      placement:
        constraints: [node.labels.tenant==multi-tenant]
      restart_policy:
        condition: any
    labels:
      collectord.io/logs-eventpattern: '^\['
    environment:
      PORT: 5000
      NODE_ENV: 'production'
      DATABASE: 'mongodb://<tclinic-name>:yeuemdailau@10.117.134.9:27017/<tclinic-name>?authSource=<tclinic-name>'
    volumes:
      - /etc/localtime:/etc/localtime:ro
#volumes:   
#  media-upload:
#    driver: lizardfs

如果我使用这样的手动命令,结果是正确的。

sed -i "s/<tclinic-name>/hanoitclinic/g" clinic-api-core.yml

结果将是正确的,如下所示:

version: '3.2'
services:
  # core backend service
  core-backend:
    image: "vany/multi-tenant-core:latest"
    deploy:
      replicas: 1
      placement:
        constraints: [node.labels.tenant==multi-tenant]
      restart_policy:
        condition: any
    labels:
      collectord.io/logs-eventpattern: '^\['
    environment:
      PORT: 5000
      NODE_ENV: 'production'
      DATABASE: **'mongodb://hanoitclinic:yeuemdailau@10.117.134.9:27017//hanoitclinic?authSource=hanoitclinic'**
    volumes:
      - /etc/localtime:/etc/localtime:ro
#volumes:   
#  media-upload:
#    driver: lizardfs

但是如果我使用 shelljs,这样的代码(我从客户端传递的 ClinicName = "hanoitclinic"

 var shell = require('shelljs');
shell.sed('-i', '<tclinic-name>', clinicName, "clinic-api-core.yml");

结果不正确,它只替换一次:

 DATABASE: 'mongodb://hanoitclinic:yeuemdailau@10.117.134.9:27017/<tclinic-name>?authSource=<tclinic-name>'

请看一下。谢谢

4

1 回答 1

1

根据 ShellJS文档中的示例(以及此处

sed([options,] search_regex, replacement, file [, file ...])

search_regex可以是正常的正则表达式replace(),所以我建议使用global 标志:

shell.sed('-i', /<tclinic-name>/g, clinicName, "aibolit-api-core.yml");
于 2021-03-11T16:29:02.470 回答