Replace special characters with Escape characters?

i need to replace the any special characters with escape characters like below.

test!=123-> test\!\=123

!@#$%^&*()-= to be replaced by

\!\@\#\$\%\^\&\*\(\)\-\=
echo '!@#$%^&*()-' | sed "s/[!@#$%^&*()-]/\\\&/g"
\!\@\#\$\%\^\&\*\(\)\-

You listed = to be enclosed by / / too, but in your example it is not. Remove it from the pattern list maybe. Anyway maybe this is what you are looking for:

$> echo 'test!=123'| sed 's_[!@#$%^&*()-=]_\/&\/_g'
test/!//=/123
echo 'test!=123' | sed 's:[!@#$%^&*()=-]:\\&:g'

And just one more.... :wink:

export var1='One Way To !@#$%^&*()-= Do It'

echo $var1 | sed 's#\([]\!\(\)\#\%\@\*\$\/&\-\=[]\)#\\\1#g'

One Way To \!\@\#\$\%^\&\*\(\)-\= Do It

@Laknar

Just for education purpose :

The trick is that in between a list [.....] some character have a special meaning :

The hyphen - is usually used to define and interval example : [0-9]

That is the reason why, in order to make it interpreted as litteral , it should be placed at a edge of the list (beginning or end) consider :

$ echo '!@#$%^&*()-' | sed 's/[-!@#$%^&*()]/\\&/g'
\!\@\#\$\%\^\&\*\(\)\-
$ echo '!@#$%^&*()-' | sed 's/[!@#$%^&*()-]/\\&/g'
\!\@\#\$\%\^\&\*\(\)\-

There is another special case within a list [......] :
The closing square bracket ]
This special closing square bracket - to be taken as litteral (so that the substitution will apply)- needs to be setup at the very first position in the list otherwise it is take as end of the list or unexpected behaviour may occure.

Consider the following example :

$ echo '!@#[]$%^&*()-' | sed 's/[]!@#[$%^&*()-]/\\&/g'
\!\@\#\[\]\$\%\^\&\*\(\)\-
$ echo '!@#[]$%^&*()-' | sed 's/[-!@#[$%^&*()]]/\\&/g'
!@#\[]$%^&*()-
$ echo '!@#[]$%^&*()-' | sed 's/[-!@#[]$%^&*()]/\\&/g'
!@#[]$%^&*()-

@laknar & off topic
Just wondered why you would want to do this?

Look at the hyphen : the adding of backslash failed ...

Try this

echo 'test!=123'  |  sed 's/[^[:alnum:]]/\\&/g'