Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

4 Answers 4

up vote 14 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
add comment

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

%s/\(\n\n\)\n\+/\1/
share|improve this answer
add comment

If in Vim, just do this:

:%!cat -s
share|improve this answer
2  
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
add comment

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
add comment

Your Answer

 
discard

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.