Remove blank lines from text file

I have a text file with empty lines. The meaning of lines that have nothing on them and just take up space.

It looks like this:

The quick brown fox jumped over the lazy dog 

and I need it to look like this:

 The quick brown fox jumped over the lazy dog 

How to delete these empty lines and take only lines with contents and write them to a new file?

Here is what I know how to do this:

 $file = fopen('newFile.txt', 'w'); $lines = fopen('tagged.txt'); foreach($lines as $line){ /* check contents of $line. If it is nothing or just a \n then ignore it. else, then write it using fwrite($file, $line."\n");*/ } 
+4
source share
7 answers

If the file is not too large:

 file_put_contents('newFile.txt', implode('', file('tagged.txt', FILE_SKIP_EMPTY_LINES))); 
+7
source

This uses the foreach solution to simply remove empty lines (without writing to a file):

 $lines = file('in.txt'); foreach ($lines as $k => $v) { if (!trim($v)) unset($lines[$k]); } 
+2
source
 file_put_contents('newFile.txt', preg_replace( '~[\r\n]+~', "\r\n", trim(file_get_contents('tagged.txt')) ) ); 

I like \r\n :)

+2
source
 file_put_contents( "new_file.txt", implode( "", array_filter( file("old_file.txt") )) ); 

This code first reads the file into an array ( file() ), filters out empty elements ( array_filter ), and then writes them to a new file. The impode delimiter is empty because file leaves \n at the end of each line.

+1
source

You can do everything in one go:

 file_put_contents('newFile.txt', preg_replace( '/\R+/', "\n", file_get_contents('tagged.txt') ) ); 
+1
source
 foreach($lines as $line) { if ($line!=='') $file.write($line); } 
0
source

try with strpos. search for \ n. if the return value is 0, you turn off the line

-1
source

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


All Articles