1

I am writing a shell script where I input a value and want to use the value for some other commands. My problem is that I want to escape this value.

For example, if I input http://example.com in the following script

echo "Input a value for my_value"
read my_value

echo $my_value

It will result in http://example.com

But the result I wish is http\:\/\/example\.com

How do I achieve this?


The command I'm trying to run is

sed -i s/url/$my_value/g somefile.html

without the escape it becomes sed -i s/url/http://example.com/g somefile.html which obviously is a syntax error..

han4wluc
  • 1,179
  • 1
  • 14
  • 26

4 Answers4

2

There is no need to escape / in the variable, you can use an alternate regex delimiter in sed:

sed -i "s~url~$my_value~g" somefile.html
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

You can use other characters to split the s arguments. I like the ,

sed -i 's,url,http://example.com,g'

. If you really want it you can use sed to replace the / in the argument, before executing

url=$(echo "http://example.com"|sed 's,/,\\/,g')
sed -i 's/url/'"$url"'/g' input
ikrabbe
  • 1,909
  • 12
  • 25
0

To add a slash before any non-alphanumeric character:

$ my_value=http://example.com
$ my_value=$(sed 's/[^[:alnum:]]/\\&/g' <<<"$my_value")
$ echo "$my_value"
http\:\/\/example\.com

However, if you want to then use that in a sed command, you need to double the backslashes

$ echo this is the url here | sed "s#url#$my_value#g"
this is the http://example.com here
$ echo this is the url here | sed "s#url#${my_value//\\/\\\\}#g"
this is the http\:\/\/example\.com here
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

The problem you are having is that you just want to replace one literal string with a different literal string but sed CANNOT operate on strings. See Is it possible to escape regex metacharacters reliably with sed for a sed workaround but you might be better off just using a tool that can work with strings, e.g. awk:

awk -v old='original string' -v new='replacement string' '
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
    { print }
' file
Community
  • 1
  • 1
Ed Morton
  • 188,023
  • 17
  • 78
  • 185