与Bash
和SED
我试图用URL替换js文件中的两个字符串。在sed命令中跳出正斜杠
当我运行.sh脚本时,应该插入的两个url是input params。
./deploy.sh https://hostname.com/a/index.html https://hostname2.com/test
然而,为了使我的sed命令这可用我要逃避所有向前斜杠:\\
?
./deploy.sh https:\\/\\/hostname.com\\/a\\/index.html https:\\/\\/hostname2.com\\/test
如果他们是在Mac OSX塞拉利昂躲过了这场SED命令的工作现在
APP_URL=$1
API_URL=$2
sed "s/tempAppUrl/$APP_URL/g;s/tempApiUrl/$API_URL/g" index.src.js > index.js
我不想逃脱插入网址作为参数,可以我希望脚本它自我逃避正斜杠。
这是我已经试过:
APP_URL=$1
API_URL=$2
ESC_APP_URL=(${APP_URL//\//'\\/'})
ESC_API_URL=(${API_URL//\//'\\/'})
echo 'Escaped URLS'
echo $ESC_APP_URL
#Echos result: https:\\/\\/hostname.com\\/a\\/index.html
echo $ESC_API_URL
#Echos result: https:\\/\\/hostname2.com\\/test
echo "Inserting app-URL and api-URL before dist"
sed "s/tempAppUrl/$ESC_APP_URL/g;s/tempApiUrl/$ESC_API_URL/g" index.src.js > index.js
的PARAMS看起来是一样的,但是在这种情况下,SED抛出一个错误
sed: 1: "s/tempAppUrl/https:\\/\ ...": bad flag in substitute command: '\'
谁能告诉我的区别就在这里?字符串看起来是一样的,但是给出了不同的结果。
这不仅仅是'/'s,你必须转义更多的字符(例如当前正则表达式中的'''s'),但是sed不会给你大多数错误信息,只会破坏你的输出。请参阅http://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed/29626460#29626460。如果你想学习如何做一个健壮的字符串替换,然后发布一个新的问题(并且答案不会sed,因为sed不支持字符串!)。 –