5

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.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
herbertD
  • 10,657
  • 13
  • 50
  • 77

2 Answers2

12

M-x flush-lines RET ^[[:space:]]*$ RET is probably the canonical way to do that.

Stefan
  • 27,908
  • 4
  • 53
  • 82
8

^ 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.

jlahd
  • 6,257
  • 1
  • 15
  • 21
  • 2
    Thanks for the tips of ^J, I used M-x replace-regexp ^C-q C-j solved the problem. – herbertD Oct 21 '14 at 06:28
  • Your method removed all lines returns, I just want to remove the empty lines. – herbertD Oct 21 '14 at 06:31
  • 1
    True, forgot the `^` in the beginning (edited now). To match your original spec "including tabs and spaces" you do need the `[[:space:]]*` part, though. – jlahd Oct 21 '14 at 06:34