han4wluc
han4wluc

Reputation: 1189

shell script, how to escape variables?

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..

Upvotes: 1

Views: 1533

Answers (4)

Ed Morton
Ed Morton

Reputation: 203229

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

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246764

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

Upvotes: 0

ikrabbe
ikrabbe

Reputation: 1929

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

Upvotes: 2

anubhava
anubhava

Reputation: 784998

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

Upvotes: 2

Related Questions