Galladite
Galladite

Reputation: 137

Replace multiple lines of whitespace with one line using sed

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

Upvotes: -1

Views: 93

Answers (1)

potong
potong

Reputation: 58558

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.

Upvotes: 1

Related Questions