3

I want to escape a underscore in a filename with a backslash (\). So file_01.jpg would become file\_01.jpg.

I tried:

(replace-regexp-in-string "_" "\_"  "file_01.jpg" t t) 

but that produces file_01.jpg. And:

(replace-regexp-in-string "_" "\\_"  "file_01.jpg" t t)

gives file\\_01.jpg.

How can I insert a single backslash?

  • This possibly isn't the best way to do whatever it is that you need to do. What is it that requires escaped underscores in filenames? – phils Jul 19 '16 at 2:08
7

Your second example is actually correct. The resulting string contains a single backslash; it looks like a double backslash because it's printed as an Emacs Lisp string.

You can see this by converting the string into a list of one-character strings:

(mapcar 'string (replace-regexp-in-string "_" "\\_" "file_01.jpg" t t))

This returns:

("f" "i" "l" "e" "\\" "_" "0" "1" "." "j" "p" "g")

"\\" is a string with one character, a backslash. It is displayed with two backslashes because that's required by Emacs Lisp string syntax.

  • The reason I want this is because I'm converting a org document to md with pandoc. The underscore interprets the following 01 as subscript. It works correct if I escape the underscore. "file\_01.jpg still gives me "file\" and then "01" as underscore. I guess i need something that gives me this list of one-character string: ("f" "i" "l" "e" "_" "0" "1" "." "j" "p" "g") – workspace Jun 24 '15 at 16:02
  • That would be (mapcar 'string "file_01.jpg"), if I'm understanding correctly. – legoscia Jun 24 '15 at 16:04
  • sorry I meant ("f" "i" "l" "e" "\_" "0" "1" "." "j" "p" "g"). – workspace Jun 24 '15 at 18:57
  • What should the "\_" string contain — a backslash, an underscore, or both? – legoscia Jun 24 '15 at 20:25
  • 1
    OK. I got it. sorry very new in elsip. when I insert the string with the double backslash i get the result i want. thank for your persitance! – workspace Jun 25 '15 at 8:45
0

Use (replace-string "_" "\\_"), maybe in combined with-temp-buffer to put the string in.

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.