Home > Enterprise >  Using variables in a sed command - sed -e exception: unknown option to `s'
Using variables in a sed command - sed -e exception: unknown option to `s'

Time:05-27

Lets say we have two variables

var1='<tr><th>Text</th><tr>
var2='<tr><th>Text</th><td>No applications<td><tr>'

if first(var1) text part is available in my file I want to replace it with second (var2) text part.

The command I have written is

sed -i -e "s/$var1/$var2/g" mypage.html

this does not work and give an error message saying "- sed -e exception: unknown option to `s' " I tried removing the -e part. It also not works

How can I do this ?

CodePudding user response:

The problem is that the separator that you give to s, namely /, also occurs in $var1 and $var2. Simply choose a different separator that doesn't occur in these variables, for example |:

sed -i -e "s|$var1|$var2|g" mypage.html

CodePudding user response:

The other option to changing the s delimiter (what if you data contains that character also?) is to escape the delimiters in your variables.

Warning: leaning toothpick syndrome ahead

sed "s/${var1//\//\\\/}/${var2//\//\\\/}/g" mypage.html

Demo:

$ cat > mypage.html
<html><body><table>
<tr><th>Text</th><tr>
</table></body></html>

$ sed "s/${var1//\//\\\/}/${var2//\//\\\/}/g" mypage.html
<html><body><table>
<tr><th>Text</th><td>No applications<td><tr>
</table></body></html>
  • Related