Search code examples
regexemacsstr-replace

How to delete empty lines in a file using Emacs?


In Emacs, how to remove all empty lines (including tabs and spaces) in file?

Can M-x replace-regexp do the trick?

I can find the empty lines with regexp: ^[st]*$, but don't know how to replace it by deleting.


Solution

  • ^ and $ just match starts and ends of lines, not the actual end-of-line characters. You have the explicitly type the newline in the expression to replace it.

    To achieve your goal, replace-regexp

    ^[[:space:]]*^J
    

    with nothing (empty text). To enter ^J, first press Control and Q, then Control and J. In the entry field, this shows up as an actual line change.