开发者

Howto use sed to remove only triple empty lines?

开发者 https://www.devze.com 2023-02-04 13:23 出处:网络
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

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 tr开发者_运维问答iple empty lines and only triple empty lines.

Any help would be much appreciated.


It's as simple as:

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


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


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

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消