skywind
skywind

Reputation: 964

How to sort a data in txt file?

I have generated txt file. How to sort the lines in it by first number before | ?

It have structure like:

1|5
4|7
2|3
3|1

I try like this, but it's show error. Full code:

$str='';
    foreach ($_POST['answer'] as $num => $answer) {
        $str.="$num|".rtrim($answer)."\r\n";
    }
$data = explode("\n",$str);
sort($data,SORT_NUMERIC);
$date=date('y-m-d_H-i-s');
$fp=fopen("output/".$date."_out.txt", "w+");
$write=fwrite($fp, $data);
fclose($fp);
if ($write) echo 'Done!';

Upvotes: 0

Views: 3899

Answers (3)

Slobodan Antonijević
Slobodan Antonijević

Reputation: 2643

This is by far the fastest and most elegant solution that I have found, when I had the same problem. If you're on Linux (with exec allowed in PHP configuration) you can do the following (provided you want to sort files numerically):

exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);

Basically, execute bash command sort that sorts the lines in a file numerically. If you want to keep the data in the original file do this:

exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
exec("rm " . $pathToOriginalFile);
exec("mv " . $pathToSortedFile . " " . $pathToOriginalFile);

If you want an alphabetical sort just exclude -n (--numeric-sort) option.

exec("sort " . $pathToOriginalFile . " > " . $pathToSortedFile);

For me the command took about 3 seconds to sort 10 million lines in the file on the server.

You can find more about sort here http://www.computerhope.com/unix/usort.htm

Hope it helps.

Upvotes: 1

knittl
knittl

Reputation: 265201

$file = file('path/to/file');
sort($file, SORT_NUMERIC);
fwrite('path/to/file', join("\n", $file));

Upvotes: 3

Benjie
Benjie

Reputation: 7946

$data = trim(file_get_contents('file'));
$data = explode("\n",$data);
sort($data,SORT_NUMERIC);
$data = implode("\n",$data);

Upvotes: 2

Related Questions