There are two levels of interpretation here: the shell, and sed.
In the shell, everything between single quotes is interpreted literally, except for single quotes themselves. You can effectively have a single quotes between single quotes by writing '\'' (close single quote, one literal single quote, open single quote).
Sed uses basic regular expressions. In a BRE, the characters $.*[\]^ need to be quoted by preceding them by a backslash, except inside character sets ([…]). Letters, digits and (){}+?| must not be quoted (you can get away with quoting some of these in some implementations). The sequences \(, \), \n, and in some implementations \{, \}, \+, \?, \| and other backslash+alphanumerics have special meanings. You can get away with not quoting $^] in some positions in some implementations.
Furthermore, you need a backslash before / if it is to appear in the regex. You can choose an alternate character as the delimiter by writing e.g. s~/dir~/replacement~ or \~/dir~p; you'll need a backslash before the delimiter if you want to include it in the BRE. If you choose a character that has a special meaning in a BRE and you want to include it literally, you'll need three backslashes; I do not recommend this.
In a nutshell, for sed:
- Write the regex between single quotes.
- Use
'\'' to search for a single quote.
- Put a backslash before
$.*/[\]^ and only those characters.
In the replacement text, & and \ need to be quoted, as do the delimiter and newlines. \ followed by a digit has a special meaning. \ followed by a letter has a special meaning (special characters) in some implementations, and \ followed by some other character means \c or c depending on the implementation.
If the regex or replacement text comes from a shell variable, remember that
- the regex is a BRE, not a literal string;
- in the regex, a newline needs to be expressed as
\n;
- in the replacement text,
&, \ and newlines need to be quoted;
- the delimiter needs to be quoted.
- Use double quotes for interpolation:
sed -e "s/$BRE/$REPL/"