lets say I have a variable var="['test']"
and another variable var_1="[different]"
and I wanted to do echo "$var" | sed 's/$var/$var_1/'
the output that will be produced will be incorrect, because of the []
.
Instead of just asking how to fix this for this specific scenario, I want to ask the question, if there is a general way to use variables that contain special characters in sed.
It should be possible to create a function that converts the contents of the variable into a format that isn't problematic to sed, by escaping every problematic character.
function sed_compatible_formatting(){
sed -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' -e 's/\//g' -e 's/\./\\\./g' -e 's/\*/\\\*/' # ...
}
I do not like such a solution, as it would require passing every variable that I want to use in sed to some other variable that is compatible or doing something like sed "s/$(echo "$var" | sed_compatible
*formatting)//"
, which would be rather cumbersome. A better way would be something like sed "s/$var//"
, but unfortunately that isn't possible, however maybe a sed flag exists that I am just unaware of.