【发布时间】:2017-04-04 12:59:15
【问题描述】:
使用Bash 和SED 我试图用URL 替换js 文件中的两个字符串。
当我运行 .sh 脚本时,应该插入的两个 url 是输入参数。
./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
如果他们被转义,则此 SED 命令适用于 Mac OSX Sierra
APP_URL=$1
API_URL=$2
sed "s/tempAppUrl/$APP_URL/g;s/tempApiUrl/$API_URL/g" index.src.js > index.js
现在我不想插入转义的 url 作为参数,我希望脚本自己转义正斜杠。
这是我尝试过的:
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
参数看起来相同,但在这种情况下,SED 会抛出错误
sed: 1: "s/tempAppUrl/https:\\/\ ...": bad flag in substitute command: '\'
谁能告诉我这里的区别?字符串看起来相同,但结果不同。
【问题讨论】:
-
这不仅仅是
/s,还有很多你必须转义的字符(例如你当前正则表达式中的.s),但对于大多数人来说,sed 不会给你一个错误消息其中,它只会破坏你的输出。见stackoverflow.com/questions/29613304/…。如果您想学习如何进行健壮的字符串替换,请发布一个新问题(由于 sed 不支持字符串,因此答案将不会被 sed!)。