bulk search and replace with sed

Kurt writes:

I’ve got a text input string in unix that I want to parse and replace all of the following characters [\^$.|?*+(){} with the same character preceded by an \.

(I am trying to backslash escape all the special characters used by grep before I feed the string into grep.  Don't ask - not my original code.)

For example, "this \is an $xample" would become "this \\is an \$xample".

What would be the easiest way to do this?

I got this to work after a bit of learning ... :

sed -e "s/\([[\^$.|?*+(){}]\)/\\\\\1/g” test.txt

hope this helps someone.

This entry was posted in Linux. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>