I have file which has multiple newlines. I want to receive single newline in their place.

I know how to do it in vim(found in google query):


How can I do the same in Emacs?

Example input:

this is file
with lines


empty lines 


Example output:

this is file
with lines


empty lines 


Use C-M-% to run query-replace-regexp. This works similarly to query-replace in db48x's answer, but allows for a regular expression. Using


as input (^ matches end of line, followed by one or more newlines), and replace with a single newline.

  • 1
    To input a newline into the search/replace queries, hit C-q C-j – nanny Nov 17 '15 at 16:34

You can do it with this function:

(defun remove-extra-blank-lines ()
    "replace multiple blank lines with a single one"
    (goto-char (point-min))
    (while (re-search-forward "\\(^\\s-*$\\)\n" nil t)
      (replace-match "\n")
      (forward-char 1)))

M-% runs the command query-replace, which prompts you first for the string to find, then the string to replace matches with. The enter key would normally close each of these prompts, so you have to do something special to search for or replace a newline.

Any time you want to type a character that would ordinarily have some other effect, you can prefix it with C-q. So C-q RET will enter the literal carriage return character, which is visually represented in a buffer as ^M.

However, your text file may or may not use carriage returns to indicate newlines. Most likely it uses line feeds instead. In this case you'll want to use C-q C-J instead.

So, to put it all together: use M-% C-q C-j C-q C-j RET C-q C-j RET to replace two line-feed characters in a row with a single line-feed character.

At each match the query-replace command will ask you what to do. You can replace a single match, skip a match, or hit ! to replace all matches. There are a few other options as well.

  • Isn't it better to use ^C-q C-j C-q C-j +? Alos, C-x h to mark the whole buffer – fredtantini Nov 17 '15 at 15:21
  • Shouldn't your "put all together" command start with M-% instead of C-%? – MatthewRock Nov 17 '15 at 15:24
  • @fredtantini: query-replace doesn't use regex matching – db48x Nov 17 '15 at 15:29
  • @db48x Indeed. That was for C-M-% – fredtantini Nov 17 '15 at 15:41

You could use replace-regexp (C-M-%) to replace at least two new lines, with just one. To enter a new line, you can use C-q C-j. So: C-M-% (or M-x replace-regexp) then you replace ^C-q C-j C-q C-j + with C-q C-j

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.