0

I have a big txt file (84mb) with over 1 million lines.

I want to split it in seperate 50k lines files. How can i do it? I searched on-line but I found nothing about it.

4

2 に答える 2

1

これは、次の場所にある私のスクリプトの修正版です:巨大なテキスト ファイルを読み取り、各行をデータベースに保存します

使用法

set_time_limit(0);

// Split by Byte
splitData("b.php", __DIR__ . "/test", 1024 * 50); //Split 50Kb

// Split By line
splitLine("b.php", __DIR__ . "/test", 50000);

機能

function splitData($filename, $destination, $chunkSize) {
    $pathInfo = pathinfo($filename);
    $handle = fopen($filename, 'rb');
    $counter = 0;
    if ($handle === false) {
        return false;
    }
    while ( ! feof($handle) ) {
        $counter ++;
        $filePart = $destination . DIRECTORY_SEPARATOR . $pathInfo['filename'] . "_" . $counter . "." . $pathInfo['extension'];
        touch($filePart);
        file_put_contents($filePart, fread($handle, $chunkSize));
    }
    $status = fclose($handle);
    return $status;
}

function splitLine($filename, $destination, $lineSize) {
    $pathInfo = pathinfo($filename);
    $handle = fopen($filename, 'rb');
    $counter = 0;
    $splitCount = 0;
    if ($handle === false) {
        return false;
    }

    $content = "";
    while ( ($buffer = fgets($handle, 4096)) !== false ) {
        $content .= $buffer;
        $counter ++;

        if ($counter >= $lineSize) {
            $splitCount ++;
            $filePart = $destination . DIRECTORY_SEPARATOR . $pathInfo['filename'] . "_" . $splitCount . "." . $pathInfo['extension'];
            touch($filePart);
            file_put_contents($filePart, $content);
            $content = "";
            $counter = 0;
        }
    }
    $status = fclose($handle);
    return $status;
}
于 2012-09-13T13:17:45.407 に答える
0
<?php 
$handle = @fopen("/tmp/inputfile.txt", "r");
$maxLines = 50;
if ($handle) {
    $counter = 1;
    $fileCount = 1;
    $data = array();
    while (($buffer = fgets($handle, 4096)) !== false) {
        $data[] = $buffer;
        if(count($data) % $maxLines == 0) {
            file_put_contents("filename{$fileCount}.txt", implode("\n\r", $data));
            $data = array();
            $fileCount++;
        }
        $counter++;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}  
?>

そのようなことはうまくいくはずですが、私はそれをお勧めしませんが、それは問題を解決する良い方法ではありません.

于 2012-09-13T12:56:50.783 に答える