Emacs: how to search and replace newlines

I can’t remember where I learnt this, but I use it all the time and it’s not at all obvious.

When in the minibuffer (at the prompt for replace-string or replace-regexp, for example), enter C-q C-j for a newline (0x0D, NL).

Depending on the coding system for the buffer (DOS mode for example), you may also need to use C-q C-m for carriage return (0x0D, CR) – suddenly it makes sense where all those ^Ms come from!

This entry was posted in Uncategorized. Bookmark the permalink.

3 Responses to Emacs: how to search and replace newlines

  1. matt burns says:

    I seem to have faced the same problem more times than losing my keys or running out of toilet paper.
    I don’t use emacs but so I use the command dos2unix. Finding a command that performs the inverse I’ll leave as a fun exercise for the reader.

    • tomblench says:

      Of course real men use tr.

      I’m pretty sure emacs and most decent text editors will auto-detect line endings and do the right thing. And don’t get me started on text editors that insert a Byte Order Mark.

Leave a Reply to matt burns Cancel reply

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