How to compress 4 consecutive empty lines in one line in Perl

I am writing a Perl script to read a log to overwrite a file in a new log, deleting blank lines if I see any consecutive blank lines of 4 or more. In other words, I will have to compress any four consecutive empty lines (or more lines) into one line; but in any case, from 1, 2 or 3 lines in the file the format should remain. I tried to get a solution online, but I can only find

perl -00 -pe '' 

or

 perl -00pe0 

Also, I see an example in vim like this to remove blocks from 4 empty lines :%s/^\n\{4}// that match what I'm looking for, but that was in vim and not in Perl . Can anyone help with this? Thanks.

+4
source share
5 answers

To collapse 4+ consecutive Unix-style EOLs with one new line:

 $ perl -0777 -pi.bak -e 's|\n{4,}|\n|g' file.txt 

Alternative aroma using appearance:

 $ perl -0777 -pi.bak -e 's|(?<=\n)\n{3,}||g' file.txt 
+8
source
 use strict; use warnings; my $cnt = 0; sub flush_ws { $cnt = 1 if ($cnt >= 4); while ($cnt > 0) {print "\n"; $cnt--; } } while (<>) { if (/^$/) { $cnt++; } else { flush_ws(); print $_; } } flush_ws(); 
+1
source

The hint -0 is good, since you can use -0777 to delete the whole file in -p mode. Read more about these guys in perlrun. So, this oneliner should do the trick:

 $ perl -0777 -pe 's/\n{5,}/\n\n/g' 

If there are up to four lines in a row, nothing happens. Five new lines or more (four empty lines or more) are replaced by two new lines (one empty line). Pay attention to the /g switch here to replace more than just the first match.

Delayed code:

 BEGIN { $/ = undef; $\ = undef; } LINE: while (defined($_ = <ARGV>)) { s/\n{5,}/\n\n/g; } continue { die "-p destination: $!\n" unless print $_; } 

NTN! :)

0
source

One way to use GNU awk by setting the write separator to NUL:

 awk 'BEGIN { RS="\0" } { gsub(/\n{5,}/,"\n")}1' file.txt 

This assumes that you are a blank definition excludes spaces

0
source

It will do what you need

 perl -ne 'if (/\S/) {$n = 1 if $n >= 4; print "\n" x $n, $_; $n = 0} else {$n++}' myfile 
0
source

Source: https://habr.com/ru/post/1432683/


All Articles