bash 在 sed 命令中转义正斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40714970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:27:52  来源:igfitidea点击:

Escaping forward slashes in sed command

bashshellsed

提问by Jonathan Andersson

With Bashand SEDI'm trying to replace two strings in a js file with URL's.

随着BashSED我试图取代在URL的JS文件两个字符串。

The two urls that should be inserted is input params when I run the .sh script.

当我运行 .sh 脚本时,应该插入的两个 url 是输入参数。

./deploy.sh https://hostname.com/a/index.html https://hostname2.com/test

However to make this usable in my sed command I have to escape all forward slashes with: \\?

然而,为了使这种可用在我的sed命令我必须逃避所有斜杠用:\\

./deploy.sh https:\/\/hostname.com\/a\/index.html https:\/\/hostname2.com\/test

If they are escaped this SED command works on Mac OSX Sierra

如果它们被转义,则此 SED 命令适用于 Mac OSX Sierra

APP_URL=
API_URL=

sed "s/tempAppUrl/$APP_URL/g;s/tempApiUrl/$API_URL/g" index.src.js > index.js

Now I don't want to insert escaped urls as params, I want the script it self to escape the forward slashes.

现在我不想将转义的 url 作为参数插入,我希望脚本本身可以转义正斜杠。

This is what I've tried:

这是我尝试过的:

APP_URL=
API_URL=

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

The params looks the same but in this case the SED throws a error

参数看起来相同,但在这种情况下,SED 会引发错误

sed: 1: "s/tempAppUrl/https:\/\ ...": bad flag in substitute command: '\'

Could anyone tell me the difference here? The Strings looks the same but gives different results.

谁能告诉我这里的区别?字符串看起来相同但给出不同的结果。

回答by Cyrus

I suggest to replace

我建议更换

sed "s/regex/replace/" file

with

sed "s|regex|replace|" file

if your sed supports it. Then it is no longer necessary to escape the slashes.

如果您的 sed 支持它。然后不再需要逃避斜线。

The character directly after the sdetermines which character is the separator, which must appear three times in the scommand.

后面的s字符决定了哪个字符是分隔符,在s命令中必须出现3次。