sdknewbie
sdknewbie

Reputation: 669

Remove first and last line from files

I am brand new to PHP and I have thousands of records I need to analyze. It appears that the first 2 lines and the last line of each record need to be removed. Is there some type of line count function that I could use to put each line into an array and then delete the first two and do like a max count to get the last line and then delete that? I am at a loss and appreciate any help. Thanks.

Upvotes: 1

Views: 3708

Answers (2)

b101101011011011
b101101011011011

Reputation: 4519

<?php

$file = file("file.txt");

array_shift($file); // Removing the first line
array_shift($file); // Removing the second line

array_pop($file); // Removing last line

// Creating the new file:

$fp = fopen("newFile.txt", "a+");

for ($x=0; $x < sizeof($file); $x++)
{
fputs($fp, $file[$x]. "\n");
}

fclose($fp);

?>

Upvotes: 2

Marc B
Marc B

Reputation: 360692

Assuming you're on a Unix/Linux host, you'd be better off using some simple shell tools to do this for you. Specifically wc -l, head, and tail.

for i in *.txt; do
    lines=`wc -l $i`
    tail $(($lines - 2)) $i | head $(($lines - 1)) > /fixed/files/$i
done

not tested, YMMV, etc... but should get the idea across.

Upvotes: 3

Related Questions