本文介绍了在sed命令中转义正斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用BashSED我试图用URL替换js文件中的两个字符串.

With Bash and SED I'm trying to replace two strings in a js file with URL's.

运行.sh脚本时,应插入的两个URL是输入参数.

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

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

但是要使它在我的sed命令中可用,我必须使用\\?

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

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

如果已转义,则此SED命令可在Mac OSX Sierra上运行

If they are escaped this SED command works on 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作为参数,我希望脚本本身可以转义正斜杠.

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

这是我尝试过的:

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会引发错误

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

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.

推荐答案

我建议替换

sed "s/regex/replace/" file

使用

sed "s|regex|replace|" file

如果您的sed支持它.这样就不再需要转义斜线了.

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

s后面的字符确定哪个字符是分隔符,在s命令中该字符必须出现3次.

The character directly after the s determines which character is the separator, which must appear three times in the s command.

这篇关于在sed命令中转义正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:49