How to delete a single empty line - save multiple empty lines

I have some data where I want to save some empty lines and delete only empty lines. My data looks like this:

1

2

3

4


5


6

7

8



9

10

I would like the result to be:

1
2
3  
4


5


6
7
8



9
10

I tried working with the following commands, but I cannot get it to work:

awk ' /^$/ { print; } /./ { printf("%s ", $0); }'

AND

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

In addition, I tried to use cat -s, but this does not necessarily output empty lines. In addition, I played with sed '/^$/', but can not specify only individual lines. Any help is appreciated.

+4
source share
3 answers

Using gnu-awk is pretty simple:

awk -v RS='\n+' '{printf "%s", $0 (length(RT) != 2 ? RT : "\n")}' file

1
2
3
4


5


6
7
8



9
10
  • -v RS='\n+', 1
  • length(RT), ,
  • RT ( ), length != 2

awk:

awk -v RS='\n{3,}' '{gsub(/\n{2}/, "\n", $0); printf "%s", $0 RT}' file
+6

GNU sed ( , BSD/OSX):

$ sed -E ':a; N; $!ba; :b; s/([^\n])\n\n([^\n])/\1\n\2/g; tb' input
1
2
3
4


5


6
7
8



9
10

  • :a; N; $!ba

    .

    a - . N . $!ba , .

  • :b; s/([^\n])\n\n([^\n])/\1\n\2/g; tb

    . .

    b - . s . - , tb b.

+2

This may work for you (GNU sed):

sed '/\S/!b;n;N;/^\s*\n\s*\S/D' file

If the line is empty, print it. Otherwise, print the line and enter the next two lines, and if the first of them is empty and the second is not, delete the first and repeat.

0
source

All Articles