I have text like this:

myvariable = ABCD,

Which I want to transform to:

myvariable = "ABCD,"
"EFGH,\n" \
"IJKL,\n" \
"~subsection1\n" \
"MNOP,\n" \
"QRST,\n" \
"UVWX,\n" \

To insert a " character at the beginning of each line I do the following:

C-M-% ^.* RET "\& RET

But appending \n" \ at the end of each line is trickier. I tried:

M-x replace-regexp RET $ RET \\n\\" \\ RET

But that results in:

myvariable = ABCD,\n\" \
EFGH,\n" \

So you have to do it this way:

M-x replace-regexp RET $ RET \\n" \\ RET


My thinking was that the " character had to be escaped with \, but that's obviously not the case. Why do I have to escape \ but not "?


You can match the beginning of line with only ^ and "replace" it with ".

As for the backslash: Since the backslash is the escape character in Emacs and you want to insert a literal backslash you have to escape the escape character.

The fact that you don't have to escape the double-quote here is because you are using a command (replace-regexp). If you would be writing the regular expression as part of an Emacs Lisp program it would be a string and then you would need to escape the double-quote as well.


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.