问题描述
我正在使用 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,这样的代码(我从客户端传递的clinicalName =“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>'
请看一下。谢谢
解决方法
根据ShellJS中的示例documentation - 和here - for
sed([options,] search_regex,replacement,file [,file ...])
search_regex
可以是普通的 replace()
正则表达式,所以我建议
使用g
全局标志:
shell.sed('-i',/<tclinic-name>/g,clinicName,"aibolit-api-core.yml");