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/sdff.jar/rtets.jar/fg/gdf/ggdg/dg/adg/TextParser$2.class," | sed -e "s#\([]*^+\.\$[-]\)##g"

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

  • 2
    correct command for what? What output did you want? – Zanna Jul 25 '17 at 7:47
  • I don't like the escaping with normal sed. Extended Regex with using -E is much more familiar. – pLumo Jul 25 '17 at 7:54
  • I want to escape the special characters in above string. Like forward slash, dollar sign, singe dot , – Soumali Chatterjee Jul 25 '17 at 7:54
  • 2
    Please edit your question and show us your expected output so we can be sure we are giving you what you expect. – terdon Jul 25 '17 at 7:55

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/sdff.jar/rtets.jar/fg/gdf/ggdg/dg/adg/TextParser$2.class,' |
    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/sdff.jar/rtets.jar/fg/gdf/ggdg/dg/adg/TextParser$2.class,' | 
    perl -lne 'print quotemeta()'
  • Thanks! it is working, but can we use this for all escape characters i.e.: ;'"`#$&*?[]<>{}\ as well? – Soumali Chatterjee Jul 25 '17 at 13:01
  • @SoumaliChatterjee what do you mean? Did you try it with those characters and it failed? – terdon Jul 25 '17 at 13:02
  • @SoumaliChatterjee echo ";'\"`#$&*?[]<>{}\ " | perl -ne 'print quotemeta' – terdon Jul 25 '17 at 13:06
  • Ofcourse, with my test case, like String "abm1c/def/sdfd/sync/sdff.jar", or "abm1c/def/sdfd/" it didn't. I am trying to understand if there may be any special character, which I have missed to include? Thanks – Soumali Chatterjee Jul 25 '17 at 13:26
  • @SoumaliChatterjee no character is "special" in general. It will always depend on where you want to use them. But yes, perl's quotemeta will escape everything that isn't a simple ASCII word character (so everything that doesn't match [A-Za-z_0-9]). – terdon Jul 25 '17 at 13:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.