0

i have to find a specific range of lines in a large file, so i am use sed command in unix to do this more quickly

sed -n '500000,500100 p' "/path/to/file/file.csv"

what is the equivalent in php for this command or how i can handle this issue?, i would really appreciate sample code in PHP

  • what did you try researching before coming here? – treyBake Jan 14 '20 at 13:38
  • I want to extract a piece of a file and the solutions I found were not fast enough since it is a file larger than 2GB – Nicolas correa Jan 14 '20 at 13:41
  • What about using `exec`? https://stackoverflow.com/questions/2048961/sed-doesnt-work-with-php-exec-function – mitkosoft Jan 14 '20 at 13:42
  • that is a good idea, i really don't cross my mind, but i want know is php doesn't have a native function for that – Nicolas correa Jan 14 '20 at 13:45
  • 1
    @Nicolascorrea, yes, there it is, you can check this article:https://stackoverflow.com/questions/5775452/php-read-specific-line-from-file. However, calling `exec("sed")` would be much faster for large/huge files. – mitkosoft Jan 14 '20 at 13:51
  • @Nicolascorrea Please [edit] your question to add requested information or clarification instead of answering in comments. You should add a link to the solutions you found to be too slow. – Bodo Jan 14 '20 at 14:16

1 Answers1

1
<?php
$file = file('/path/to/file/file.csv'); // reads file into an array

if($file) //checks if file was valid
{
    for($i = 499999; $i < 500100; $i++) //loops file from 500000 to 500100 (note: array first key is 0)
    {
        if(array_key_exists($i, $file) // checks if key exists
        {
            echo $file[$i]; //prints line
        }
        else
        {
            break; // if key does not exist, the next one won't exist either -> break
        }
    }
}
spyro95
  • 136
  • 9
  • 1
    Thanks @Frank.O your solution worked!!!, but mitkosoft 's solution is much more efficient using unix 'sed' tool – Nicolas correa Jan 14 '20 at 17:37
  • Yes, you're right. I thought it is important to you, to know, how to solve this in plain php. Anyway exec / shell commands will be much more effective in nearly any case. – spyro95 Jan 15 '20 at 10:22