Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace multiple empty lines with a single empty line in bash?

Tags:

regex

bash

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 replace multiple blank lines with just a single blank line. grep/sed are line based. I've never found a BASH solution that would work on multi-line regex patterns.

like image 955
Nick Zalutskiy Avatar asked May 28 '09 18:05

Nick Zalutskiy


People also ask

Which command is used to squeeze multiple blank lines to one blank line?

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 .


2 Answers

For BSD-derived systems (including GNU):

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

cat -s 

From man page: -s --squeeze-blank: suppress repeated empty output lines.

like image 181
marco Avatar answered Sep 19 '22 15:09

marco


I just solved this problem by sed. Even if this is a 7 year old question, someone may find this helpful, so I am writing my solution by sed here:

sed 'N;/^\n$/D;P;D;' 
like image 32
WKPlus Avatar answered Sep 19 '22 15:09

WKPlus