I\'m trying to look in a variable passed to my program (the variable is $1) and to replace any special characters with quoted forms of said special character, in order to no
The problem with what you've done is that you haven't quoted your sed expressions. For example, write
sed s/\*/\\*/
either as
sed 's/\*/\\*/'
or
sed s/\*/\\\\*/
I'm not sure why do you need that elaborate function in order to escape special characters. You could define a function that would give back the escaped input string:
myescape() { printf "%q" "$1"; }
%qcauses
printfto output the corresponding argument in a format that can be reused as shell input.
Another function for passing arguments to sed:
myreplace() { sed "s/$1/$2/" <<< "$3"; }
Now you could invoke it by saying:
myreplace "$(myescape 'pattern')" "replacement" "original_string"
Example:
$ myescape() { printf "%q" "$1"; }
$ myreplace() { sed "s/$1/$2/" <<< "$3"; }
$ myreplace $(myescape 'a\^a*') 'test' 'aa\^a*aa[aaa]a'
atestaa[aaa]a