Objective: Escape or append a ‘\’ to reserved characters (e.g
*, etc) found on a string variable in bash.
Before we look at the solution, let’s take a closer look at the problem. Suppose, we have a shell variable assigned as shown below.
Now, let’s try to use the variable in
sed for search and replace. Let’s replace the occurrence of ‘
__VAR__‘ to the contents of the variable
$ echo __VAR__ | sed -e "s/__VAR__/$evar/" VAR___VAR____|_?_*_ESCAPE
As you can see, the output is wrong. The output should be the contents of the variable
$evar. We will need to escape the string found in the variable
$evar before we pass it to
The solution to insert escape sequences to the string variable is to use the shell builtin
printf function with the “
%q” format specifier as shown in the syntax below.
$ printf "%q" "$evar" VAR_\&_\\_\|_\?_\*_ESCAPE
To use it within
sed, use the following syntax.
$ echo __VAR__ | sed -e "s/__VAR__/$(printf "%q" "$evar")/" VAR_&_\_|_?_*_ESCAPE
This time, the output is the same as the contents of the variable.