Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Question more or less says it all. I'm aware that /^$/d will remove all blank lines, but I can't see how to say 'replace two or more blank lines with a single blank line'

Any ideas?

share|improve this question
up vote 18 down vote accepted

If you aren't firing vim or sed for some other use, cat actually has an easy builtin way to collapse multiple blank lines, just use cat -s.

If you were already in vim and wanted to stay there, you could do this with the internal search and replace by issuing: :%s!\n\n\n\+!^M^M!g (The ^M is the visual representation of a newline, you can enter it by hitting Ctrl+vEnter), or save yourself the typing by just shelling out to cat: :%!cat -s.

share|improve this answer
wow, did not know the -s option of cat - just a historic note, it is not in POSIX, but seems to be available in BSD and GNU cat. – maxschlepzig May 7 '11 at 20:40
Marking as 'winning' for the :%!cat -s. Learn something GNnew everyday! – Andrew Bolster May 7 '11 at 20:43

Use \n to indicate a newline in the search pattern. Use Ctrl+M in the replacement text, or a backreference. See :help pattern and :help sub-replace-special (linked from :help :s).

share|improve this answer
Can you please explain how does the search pattern? – sjmp Sep 22 '15 at 7:14
@sjmp Requirement: replace two or more blank lines with a single blank line. Implementation: replace three or more consecutive newlines with just two newlines. See the manual for an explanation of the constructs used in the command. – Gilles Sep 22 '15 at 8:21

If in Vim, just do this:

:%!cat -s
share|improve this answer
You might want to add a little detail around how this works, even if it is just a quote from the man page. – jasonwryan Nov 21 '12 at 5:22

Using Perl:

perl -00 -pe ''

-00 command line option turns paragraph slurp mode on, meaning Perl reads text paragraph by paragraph rather than line by line.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.