Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove blank lines from a text file [duplicate]

Tags:

file

php

I have a text file that has some blank lines in it. Meaning lines that have nothing on them and are just taking 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 can I remove those blank lines and take only the lines with the content and write them to a new file?

Here is what I know how to do:

$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");*/
}
like image 872
JayGatz Avatar asked Jun 16 '13 20:06

JayGatz


2 Answers

If the file is not too large:

file_put_contents('newFile.txt',
                  implode('', file('tagged.txt', FILE_SKIP_EMPTY_LINES)));
like image 156
JRL Avatar answered Sep 27 '22 18:09

JRL


file_put_contents('newFile.txt',
    preg_replace(
        '~[\r\n]+~',
        "\r\n",
        trim(file_get_contents('tagged.txt'))
    )
);

I like \r\n :)

like image 24
CodeAngry Avatar answered Sep 27 '22 17:09

CodeAngry