Q:

Bash escaping script & sed capture group

I have a strange behavior in the bash script that I don't understand.
Basically in the code below I try to escape meta-characters... 
while IFS=, read _type _content; do

  if [ -z "$patternfilter" ]; then
    if [ "$_type" == "rex" ]; then
      patternfilter="$_content"
    elif [ "$_type" == "txt" ]; then
      patternfilter="`echo "$_content" | sed -re 's/([-^[{}()*+/.,;?$|#\\])/\\\1/g' -e 's/]/\\]/g'`"
    fi
  else
    if [ "$_type" == "rex" ]; then
      patternfilter="$patternfilter|$_content"
    elif [ "$_type" == "txt" ]; then
      patternfilter="$patternfilter|`echo "$_content" | sed -re 's/([-^[{}()*+/.,;?$|#\\])/\\\1/g' -e 's/]/\\]/g'`"
    fi
  fi
done < $patternfile

The outpout give me the following : 

blabal\1bla\1blabla\1toto\1com

Instead of : 

blabal\(bla\)blabla\[toto\]\.com

If I enter directly in the console the code it works ... I miss something but I don't know what.
[root]# patternfilter="blabal(bla)blabla[toto].com"
[root]# echo "$patternfilter" | sed -re 's/([-^[{}()*+/.,;?$|#\\])/\\\1/g' -e 's/]/\\]/g'
blabal\(bla\)blabla\[toto\]\.com

A:

You cannot reliably escape characters in sed as whether or not a character needs to be escaped is context sensitive. Also, the shell is an environment from which to call tools. The standard UNIX tool to manipulate text is awk. Just have your shell call awk to do everything. By the way, your use of `...` instead of $(...) will interpret double escapes and your use of read without -r will expand escapes.
SInce awk can operate on strings as well as REs you almost certainly won't have to escape anything since the usual reason to escape chars is to try to make your tool that only works on REs work on strings, which is an impossible task.
If you tell us what you're trying to do with patternfilter along with some sample input and expected output, we can show you how to do it simply and robustly.

