Sed with & in variable

I would like to find and replace sed and replace something in a variable that contains some special characters like & .

For example, I did something like this:

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

where URL=1.1.1.1/login.php?user=admin&pass=password . I think this has become a problem because I use ? and & in its variable.

How can I search and replace?

Thanks in advance

+6
variables sed
source share
5 answers
 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|" 
+2
source share

? substitution is not a problem. & must be escaped as \& .

+1
source share

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 
+1
source share

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 want to simply replace http: // ??

+1
source share
 $ 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
source share

All Articles