从文本文件中删除空行

6

我有一个文本文件,里面有一些空白行。也就是说,这些行上没有任何内容,只是占用了空间。

它看起来像这样:

The

quick
brown

fox jumped over
the

lazy dog

我需要它看起来像这样:

并且我希望你能将其翻译成这种格式:

The
quick
brown
fox jumped over
the
lazy dog

如何去除空行并只保留有内容的行,将它们写入一个新文件?

以下是我所知道的方法:

$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");*/
}

也许你的意思是 file('tagged.txt') - Jon
str_replace() 双换行符 - user557846
2
你可以使用sed命令: sed -e '/^$/d' tagged.txt > newFile.txt - Gumbo
@Jon,你能否快速向我解释一下它们之间的区别。 - JayGatz
1
@Jon 好的,我会了解它们两个。谢谢你告诉我它们是不同的! - JayGatz
显示剩余3条评论
7个回答

11

如果文件不太大:

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

它很长,有200k行,但只是文本,所以并不是那么大。 - JayGatz
php文档关于file_put_contents()的说明:“_您还可以将数据参数指定为单维数组。这相当于file_put_contents($filename,implode('',$array))。_”,因此只需省略对implode()函数的调用即可使代码更简洁。 - fietserwin
这对我没用。FILE_SKIP_EMPTY_LINES 不会有任何魔法。 - kishor10d

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

我喜欢\r\n :)


3
这里提供了一种基于foreach的解决方案,可以仅过滤掉空行(而不用写入文件):
$lines = file('in.txt');
foreach ($lines as $k => $v) {
    if (!trim($v))
        unset($lines[$k]);
}

2
你可以一次性完成整个操作:
file_put_contents('newFile.txt',
    preg_replace(
        '/\R+/',
        "\n",
        file_get_contents('tagged.txt')
    )
);

1
file_put_contents(
  "new_file.txt",
  implode(
    "", 
    array_filter(
      file("old_file.txt")
    ))
);

这段代码首先将文件读入数组中(file()),过滤掉空元素(array_filter),然后将它们写入新文件。implode分隔符为空,因为file会将每行末尾的\n字符保留下来。

0
foreach($lines as $line) {
    if ($line!=='') $file.write($line);
}

0

尝试使用strpos。搜索\n。如果返回值为0,则取消设置该行


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接