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.
1 |
$ evar='VAR_&_\_|_?_*_ESCAPE' |
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 $evar
.
1 2 |
$ 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 sed
.
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.
1 2 |
$ printf "%q" "$evar" VAR_\&_\\_\|_\?_\*_ESCAPE |
To use it within sed
, use the following syntax.
1 2 |
$ echo __VAR__ | sed -e "s/__VAR__/$(printf "%q" "$evar")/" VAR_&_\_|_?_*_ESCAPE |
This time, the output is the same as the contents of the variable.