原创线路 -
mongoose.connect('mongodb://localhost/Dbname', {useNewUrlParser: true, useFindAndModify: false })
需要更换-
mongoose.connect('mongodb://username:[email protected]:27017,host2.localhost.com:27017,host3.localhost.com:27017/DBname?authSource=admin&w=1&replicaSet=replicaname&readPreference=secondaryPreferred&retryWrites=true',{useNewUrlParser: true, useFindAndModify: false })
我们尝试通过下面的命令替换此行
sed -i 's+mongodb://localhost/Dbname+mongodb://username:[email protected]:27017,host2.localhost.com:27017,host3.localhost.com:27017/DBname?authSource=admin\\\&w=\\\1&replicaSet=replicaname&readPreference=secondaryPreferred\\&retryWrites=true/g' app.js
我们得到了不同的输出。
mongoose.connect('mongodb://username:[email protected]:27017,host2.localhost.com:27017,host3.localhost.com:27017/DBname?authSource=admin\mongodb://localhost/Dbnamew=1\mongodb://localhost/DbnamereplicaSet=replicaname\mongodb://localhost/DbnamereadPreference=secondaryPreferred\mongodb://localhost/DbnameretryWrites=true', {useNewUrlParser: true, useFindAndModify: false })
答案1
我提供了两种方法来实现你的目标。棘手的部分是如何处理&
字符串文字(參考,參考)。我假设文件test.txt
包含你的基本字符串。
awk -v old="mongodb://localhost/Dbname" -v new="mongodb://username:[email protected]:27017,host2.localhost.com:27017,host3.localhost.com:27017/DBname?authSource=admin&w=1&replicaSet=replicaname&readPreference=secondaryPreferred&retryWrites=true" 's=index($0,old){$0=substr($0,1,s-1) new substr($0,s+length(old))} 1' test.txt
awk -v old="mongodb://localhost/Dbname" '{ gsub(old, "mongodb://username:[email protected]:27017,host2.localhost.com:27017,host3.localhost.com:27017/DBname?authSource=admin\\&w=1\\&replicaSet=replicaname\\&readPreference=secondaryPreferred\\&retryWrites=true") ; print $0 }' test.txt
还有一个更灵活的版本,允许使用其他搜索字符串。这里棘手的部分是如何处理'
作为字段分隔符的awk
(參考)。
awk 'BEGIN { FS = "'\''" } ; { gsub($2, "mongodb://username:[email protected]:27017,host2.localhost.com:27017,host3.localhost.com:27017/DBname?authSource=admin\\&w=1\\&replicaSet=replicaname\\&readPreference=secondaryPreferred\\&retryWrites=true") ; print $0 }' test.txt