tags:

views:

575

answers:

9

I have a file that contains:

something



something else

something else again

I need a bash command, sed/grep w.e that will produce the following output

something

something else

something else again

In other words, I need to remove multiple blank lines with just a single blank line. gred/sed are line based. I've never found a BASH solution that would work on multi-line regex patterns. Any suggestions?

A: 

Use python:

s = file("filename.txt").read()
while "\n\n\n" in s: s = s.replace("\n\n\n", "\n\n")
import sys
sys.stdout.write(s)
Jonas Kölker
A: 

Super easy to do with vim. Just open the file and type the following:

:%s/\n\n\n*/\r\r/

That will reduce all blocks of more than 2 new lines to 2 new lines. Hope this helps!

Carl Sverre
+1  A: 

Actually, if you replace multiple newlines with a single newline, the output would be:

something
something else
something else again

You can achieve this by:

sed /^$/d FILE
Can Berk Güder
A: 

I take it that you'll probably want to remove lines that only have whitespace.

That can be done with:

sed /^[:space:]*$/d FILE
Clue Less
+2  A: 

A solution with awk, which replaces several blank lines with a single blank line:

awk 'BEGIN{bl=0}/^$/{bl++;if(bl==1)print;else next}/^..*$/{bl=0;print}' myfile
mouviciel
+1: Great minds think alike :P
Dan Moulding
+1  A: 

Usually, if I find that sed can't do something I need, I turn to awk:

awk '
BEGIN {
    blank = 0;
}

/^[[:blank:]]*$/ {
     if (!blank) {
          print;
     }
     blank = 1;
     next;
}

{
     print;
     blank = 0;
}' file
Dan Moulding
Your solution is more readable!
mouviciel
+5  A: 

grep -A1 . | grep -v "^--$"

This grep solution works assuming you want the following:

Input

line1

line2
line3


line4



line5

Output

line1

line2
line3

line4

line5
biggusjimmus
Perfect.Thank you!
Nick
I like it, very elegant solution
duckyflip
Frickin' brilliant, actually. I wouldn't have come up with this in a million years. Nice work. A _slightly_ more robust version goes like this of course (to handle non-empty blank lines): grep -v -A1 '^[[:blank:]]*$' <file> | grep -v '^--$'
Dan Moulding
A: 

Pipelining it to |uniq may be solution (if other than empty lines don't duplicate)

mateusza
+2  A: 

You just need cat with the -s option which causes it to remove repeated empty lines from its output:

cat -s

marco
Duh. Perfect solution.
Nick