0

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.

  • Use Perl instead of sed. It has real variables and even things like [quotemeta](https://perldoc.pl/quotemeta) (e.g. https://stackoverflow.com/a/67121185/1030675). – choroba Apr 01 '23 at 12:47
  • I believe you need to read [this](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed) – markalex Apr 01 '23 at 12:48
  • The best answer to `if there is a general way to use variables that contain special characters in sed` is IMHO - don't do that. Use `awk` instead since, unlike `sed`, `awk` has functionality to work with literal strings and is a mandatory POSIX tool that exists on all Unix boxes, just like `sed`. If you'd like to know how to do what you want to do using `awk` (or just in general using Unix tools), rather than specifically how to do it with `sed`, then ask a new question about that. – Ed Morton Apr 01 '23 at 12:49

0 Answers0