Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

escape special character using sed not working

Writer Matthew Harrington

I know lot of questions have been written about it, but didn't work for me. I am working in bash, and would like replace a string with escaped special characters:

echo "abm1c/def/sdfd/sync/" | sed -e "s#\([]*^+\.\$[-]\)##g"

Obviously output was incorrect. Can you please provide me with the correct sed command.

4

1 Answer

Your regular expression is wrong. It looks like you are trying to use \( \) to define a character class. You can't. Those are capture groups, they let you refer to what was matched inside them as \1 (or \2, \3 for subsequent groups). A character class is defined using []. What you want to do is capture any match of the character class to replace it with itself escaped:

$ echo 'abm1c/def/sdfd/sync/ | sed -e 's#\([]*^+.$[/]\)#\\\1#g'

Note that you aklso need the ] to be the first character in the character class. Otherwise, it is assumed to be the closing bracket. And you don't need to escape . or $ when they're within a character class.

Finally, you could do this sort of thing more simply by using perl's quotemeta:

$ echo 'abm1c/def/sdfd/sync/ | perl -lne 'print quotemeta()'
abm1c\/def\/sdfd\/sync\/sdff\.jar\/rtets\.jar\/fg\/gdf\/ggdg\/dg\/adg\/TextParser\$2\.class\,
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy