开发者

sed with & in variable

开发者 https://www.devze.com 2022-12-16 13:57 出处:网络
I would like to search and replace with sed and replace with something in a variable which is containing some specials symbols like &.

I would like to search and replace with sed and replace with something in a variable which is containing some specials symbols like &.

For example I done something like that:

sed "s|http://.*|http://$URL|"

where URL=1.1.1.1/login.php?user=开发者_开发知识库admin&pass=password. I thinks it became a problem because I use ? and & in my variable.

How can I do my search and replace?


URL="1.1.1.1/login.php?user=admin&pass=password"
URL=$(echo "$URL" | sed 's/&/\\&/')    # substitute to escape the ampersand
echo "$OTHER" | sed "s|http://.*|http://$URL|"


? in the substitution is not a problem. & needs to be escaped as \&.


The following worked for me (in a bash script):

URL="1.1.1.1/login.php?user=admin\\&pass=password"

echo "http://something" | sed -e "s|http://.*|http://$URL|"

The output was:

http://1.1.1.1/login.php?user=admin&pass=password


use awk

URL="1.1.1.1/login.php?user=admin&pass=password"
awk -vurl="$URL" '/http:\/\//{  gsub("http://" , "http://"url) }1' file

but are you really sure you just want to substitute http:// ??


$ URL="1.1.1.1/login.php?user=admin&pass=password"
$ echo "http://abcd" | sed -e "\|http://.*|c$URL"
1.1.1.1/login.php?user=admin&pass=password
0

精彩评论

暂无评论...
验证码 换一张
取 消