Linux – sed command returning “sed: bad option in substitution expression”

bashcommand linelinuxscriptsed

For example:- I have a file named file.txt

$ cat file.txt
$key

I have a environment variable, for eg: $key in a text file

and lets say $key = 1234, so I can replace the value with the below command

sed -i 's/$key/'"$key"'/' file.txt 

and it becomes

$ cat file.txt
1234

My problem is that if the value for

$key = 1/2/3/4

I'm not able to run the below command

sed -i 's/$key/'"$key"'/' file.txt  

It will give an error

sed: bad option in substitution expression

Because of the slash it's breaking. I can solve it by giving the value directly but I don't want to use it in that way.

sed -i 's/$key/1\/2\/3\/4/' file.txt 

Best Answer

The problem has to do with the fact that the sed delimiter is / and it collides with the text in $key. To solve it, use another delimiter. For example, #:

$ key="1/2/3/4"
$ echo 1/2/3/4 | sed "s#$key#\"$key\"#" 
"1/2/3/4"

Or

$ echo "hello this is 1/2/3/4 yeah" | sed "s#$key#\"$key\"#"
hello this is "1/2/3/4" yeah

Interesting reading: What delimiters can you use in sed?. Spoiler: almost everything!

Related Question