Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress 4 consecutive blank lines into one single line in Perl

Tags:

perl

I'm writing a Perl script to read a log so that to re-write the file into a new log by removing empty lines in case of seeing any consecutive blank lines of 4 or more. In other words, I'll have to compress any 4 consecutive blank lines (or more lines) into one single line; but any case of 1, 2 or 3 lines in the file will have to remain the format. I have tried to get the solution online but the only I can find is

perl -00 -pe ''

or

perl -00pe0  

Also, I see the example in vim like this to delete blocks of 4 empty lines :%s/^\n\{4}// which match what I'm looking for but it was in vim not Perl. Can anyone help in this? Thanks.

like image 521
Grace Avatar asked Jan 16 '23 15:01

Grace


1 Answers

To collapse 4+ consecutive Unix-style EOLs to a single newline:

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

An alternative flavor using look-behind:

$ perl -0777 -pi.bak -e 's|(?<=\n)\n{3,}||g' file.txt
like image 124
Zaid Avatar answered Jan 30 '23 23:01

Zaid