G7fya
G7fya

Reputation: 2095

Howto use sed to remove only triple empty lines?

Howto use sed to remove only triple empty lines?

For example:

MyText.txt

line1

line2


line3



line4

with the use of sed i want the result to look like this
MyText.txt

line1

line2


line3
line4

I was able to delete double empty lines with

sed -i '/^$/{
N
/^\n$/D
}' MyText.txt

However my goal is to delete triple empty lines and only triple empty lines.

Any help would be much appreciated.

Upvotes: 5

Views: 1867

Answers (4)

Thor
Thor

Reputation: 47189

If you allow awk solutions, you could do it like this:

awk -v RS='\n\n\n\n' 1 Text.txt

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360445

It's as simple as:

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

Upvotes: 5

zwol
zwol

Reputation: 140788

It's not sed, but it's a whole lot shorter than what you can do with sed:

$ printf 'a\nb\n\nc\n\n\nd\n' | 
  perl -e 'undef $/; $_ = <>; s/\n\n\n/\n/g; print'
a
b

c
d

Upvotes: 2

marco
marco

Reputation: 4675

The following code removes only three (neither less nor more) consecutive empty lines:

$ printf "%s\n" foo "" bar "" "" baz "" "" "" cow "" "" "" "" moe |
      sed '
        /^$/{ 
            N;
            /^\n$/{
                N;
                /^\n\n$/{
                    $ d; 
                    N;
                    s/\n\n\n\(.\)/\1/
                }
            }
        }' 
foo

bar


baz
cow




moe

Upvotes: 0

Related Questions