Bash – Escaping multiple backticks in a sed call

bashquotingsedshell

I need to perform search and replacement iteratively in several SQL statements:

From:

CREATE TABLE `Old_Name` (

To:

ALTER TABLE `Old_Name` RENAME TO `New_Name`

The above query contains backticks `. I tried doing the following

sed -i -r "s/CREATE TABLE \`$search\` \(/ALTER TABLE \`$search\` RENAME TO \`$replacement\`/g" /query.txt;

It creates an enter on the command line instead. But if I add a space behind $replacement, it runs normally. But I do not want the space after New_Name.

Note, I do not know whether this is actually caused by the backticks or it could be a variable name interpolation problem. Regardless the case, how can I solve this issue?

Best Answer

To reduce the escaping to the minimum, I suggest to use single quotes with sed, like in

sed 's/pattern/repl/g'

(in single quotes you can freely use the backtick without any fear and without escaping).
If you need to use shell variable in the sed script, put together single quotes and double quotes like in the following example

var="bbb"
thing=foo
sed 's/aaa'"${var}"'ccc/some'"${thing}"'else/g'

that could be better seen as the following concatenation

's/aaa' + "${var}" + 'ccc/some' + "${thing}" + 'else/g'
Related Question