Martin
Martin

Reputation: 1197

Squeeze multiple empty lines with sed

I have a file with empty lines and section of animal names:

$ cat animals2 



cat
dog
elephant
rhino


snake
hippo

eagle
camel
mouse



$ 

I would like to remove all the empty lines expect one, i.e. output should be:

$ cat animals2 

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

$ 

..or:

$ cat animals2 

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse
$ 

My ideas was to process the file with sed and:

Is there a way to compare pattern space with hold space in sed?

Upvotes: 0

Views: 456

Answers (3)

Jotne
Jotne

Reputation: 41460

Using -s with cat may be the simplest solution:

cat -s animals2

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

From man cat:

-s, --squeeze-blank

suppress repeated empty output lines


This perl will also do:

perl -00pe0 < animals2

Upvotes: 2

potong
potong

Reputation: 58528

This might work for you (GNU sed):

sed 'N;/^\n$/!P;D' file

Keep two lines in the pattern space and print the first one only when both are not empty.

Upvotes: 2

fedorqui
fedorqui

Reputation: 290235

As it is multiline processing, awk can do it more efficiently:

awk '!NF {f=1; next} f {print ""; f=0} 1' file

It returns:


cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

Explanation

  • !NF {f=1; next} if there are no fields --> the line is empty --> we set a flag on and we jump to the next line without further actions.
  • f{print ""; f=0}` if the flag is on and we arrive here, it means that the current line has some content. Hence, we print an empty line and deactivate the flag.
  • 1 perform the default awk action: print the current line.

Upvotes: 3

Related Questions