Replace multiple lines of whitespace with one line using sed

93 Views Asked by At

How could I use sed to replace multiple lines of whitespace (including tabs and spaces) with just one empty line?

Example input:

Line 1

<Space><Space>


Line 2
<Tab>
Line 3
Line 4

Desired output:

Line 1

Line 2

Line 3
Line 4
1

There are 1 best solutions below

0
potong On

This might work for you (GNU sed):

sed 'N;s/^[[:blank:]]*$//mg;/^\n$/!P;D' file

Append the next line.

Remove any spaces or tabs from blank lines.

If the first line of the possible two is empty do not print.

Delete upto and including the first newline or if a newline is not present, delete the line.

N.B. The P and D commands are special.