z.rubi
z.rubi

Reputation: 327

Replace multiple newlines with just 2 newlines using unix utilities

I have tried to look for the correct way to implement this, reading from stdin and printing to stdout. I know that I can use squeeze (-s) to delete multiple lines of the same type, but I want to leave two newlines in the place of many, not just one. I have looked into using uniq as well, but am unsure of how to. I know that fold can also be used, but I cannot find any information on the fold version I want, fold (1p).

So, if I have the text as input:

    A B C D 



    B C D E

I would want the output to instead be

    A B C D 

    B C D E 

Upvotes: 3

Views: 1701

Answers (2)

hek2mgl
hek2mgl

Reputation: 158230

You can use awk like this:

awk 'BEGIN{RS="";ORS="\n\n"}1' file

RS is the input record separator, ORS is the output record separator.

From the awk manual:

If RS is null, then records are separated by sequences consisting of a newline plus one or more blank lines

That means that the above command splits the input text by two or more blank lines and concatenates them again with exactly two newlines.

Upvotes: 6

RavinderSingh13
RavinderSingh13

Reputation: 133760

Following awk may help you on same.

awk -v lines=$(wc -l < Input_file) 'FNR!=lines && NF{print $0 ORS ORS;next} NF' Input_file

OR

awk -v lines=$(wc -l < Input_file) 'FNR!=lines && NF{$0=$0 ORS ORS} NF' Input_file

Upvotes: 0

Related Questions