Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sed to remove only double empty lines?

Tags:

regex

linux

sed

I found this question and answer on how to remove triple empty lines. However, I need the same only for double empty lines. Ie. all double blank lines should be deleted completely, but single blank lines should be kept.

I know a bit of sed, but the proposed command for removing triple blank lines is over my head:

sed '1N;N;/^\n\n$/d;P;D'

like image 548
marlar Avatar asked Sep 26 '12 09:09

marlar


People also ask

How remove blank lines sed?

The d command in sed can be used to delete the empty lines in a file. Here the ^ specifies the start of the line and $ specifies the end of the line. You can redirect the output of above command and write it into a new file.

How do I delete unnecessary lines?

Delete lines or connectorsClick the line, connector, or shape that you want to delete, and then press Delete. Tip: If you want to delete multiple lines or connectors, select the first line, press and hold Ctrl while you select the other lines, and then press Delete.

Which option from sed command is used to delete 2nd line in a file?

Delete lines other than the first line or header line Use the negation (!) operator with d option in sed command. The following sed command removes all the lines except the header line.

How do I remove blank lines in grep?

By Using [: space:]grep's –v option will help print lines that lack blank lines and extra spacing that is also included in a paragraph form. You will see that extra lines are removed and output is in sequenced form line-wise. That's how grep –v methodology is so helpful in obtaining the required goal.


2 Answers

This would be easier with cat:

cat -s 
like image 54
DerMike Avatar answered Sep 18 '22 20:09

DerMike


I've commented the sed command you don't understand:

sed '     ## In first line: append second line with a newline character between them.     1N;     ## Do the same with third line.     N;     ## When found three consecutive blank lines, delete them.      ## Here there are two newlines but you have to count one more deleted with last "D" command.     /^\n\n$/d;     ## The combo "P+D+N" simulates a FIFO, "P+D" prints and deletes from one side while "N" appends     ## a line from the other side.     P;     D ' 

Remove 1N because we need only two lines in the 'stack' and it's enought with the second N, and change /^\n\n$/d; to /^\n$/d; to delete all two consecutive blank lines.

A test:

Content of infile:

1   2 3  4    5  6   7 

Run the sed command:

sed '     N;     /^\n$/d;     P;     D ' infile 

That yields:

1 2 3  4  5  6 7 
like image 20
Birei Avatar answered Sep 21 '22 20:09

Birei