Another.Chemist
Another.Chemist

Reputation: 2559

Substitute two empty lines in a file with one empty line

This is the input of example1:

a


b

And the output:

a

b

This is the input of example2:

a




b

And the output:

a


b

But, with a huge file. What I have tried: sed 's/\n\n/\n/g' file amd cat file | tr '\n' '\t' | sed 's/\t\t/\t/g' | tr '\t' '\n'

Upvotes: 1

Views: 165

Answers (3)

Philipp Grigoryev
Philipp Grigoryev

Reputation: 2118

Also possible with sed

sed '/^$/N;/^\n$/ s/\n//' <your_filename>

will read the next (after an empty) line into the pattern space and, if it's also empty, remove \n

Upvotes: 2

dawg
dawg

Reputation: 103714

If you specifically want two \n\n replaced with one \n, just set the RS in gawk to do that:

gawk 'BEGIN{RS="\n\n"} 1' file

If you want runs of \n replaced, any number, with a single \n set awk to paragraph mode:

awk 'BEGIN{RS="" } 1'

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203169

sed reads 1 \n-terminated line at a time so you can't do s/\n\n/anything since there will never be any \ns in the buffer.

Just use awk:

awk -v RS= '1' file

The above will replace all sequences of empty lines by a single blank line. If that's not what you need then update your example.

Upvotes: 0

Related Questions