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,#
:Or
Interesting reading: What delimiters can you use in sed?. Spoiler: almost everything!