views:

162

answers:

5

hi,

I would like to search and replace with sed and replace with something in a variable wich 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?

Thanks in advance

A: 

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

Ignacio Vazquez-Abrams
yes i know.But I can"t add \ in my variable (or I don't know how to do it with another regexp).
pl0nk001
What variable are you talking about? If you want to escape \, you have to do it like this \\.
Balon
ghostdog74
yes that's what i mean =)
pl0nk001
... Couldn't you just use sed to replace it?
Ignacio Vazquez-Abrams
+1  A: 

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
pavium
I think OP can't add the backslash manually.
ghostdog74
Hmm, I think you're right, but I'll have to come back to this twist, it's getting late.
pavium
+1  A: 

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:// ??

ghostdog74
A: 
$ 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
Damodharan R
A: 
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|"
Dennis Williamson