Question

I have a very large text file and all I need to do is remove one single line from the top of the file. Ideally, it would be done in PHP, but any unix command would work fine. I'm thinking I can just stream through the beginning of the file till I reach \n, but I'm not sure how I do that.

Thanks, Matt Mueller

Was it helpful?

Solution

sed -i -e '1d' file will do what you want.

  • -i indicates "in-place"
  • -e means "evaluate this expression"
  • '1d' means, delete the first line

OTHER TIPS

you can use a variety of tools in *nix. A comparison of some of the different methods on a file with more than 1.5 million lines.

$ wc -l < file4
1700589

$ time sed -n '2,$p' file4 > /dev/null

real    0m2.538s
user    0m1.787s
sys     0m0.282s

$ time awk 'NR>1' file4 > /dev/null

real    0m2.174s
user    0m1.706s
sys     0m0.293s

$ time tail -n +2 file4 >/dev/null

real    0m0.264s
user    0m0.067s
sys     0m0.194s

$time  more +2 file4 > /dev/null

real    0m11.771s
user    0m11.131s
sys     0m0.225s

$ time perl -ne 'print if $. > 1' file4 >/dev/null

real    0m3.592s
user    0m3.259s
sys     0m0.321s

If your file is flat, you can use sed '1d' file > newfile

Assuming tail from GNU coreutils:

tail -n +2 file > newfile
tail -n +2 < source > destination

Tail with positive number outputs everything starting with N-th line.

Try the following command:

sed -n '2,$p' file

I don't know how big is your file, but did you try awk 'NR > 1' {print} ?

I'm a bit rusty on perl, but this might do the trick:

#!/usr/bin/perl
$first = true;
while (<>)
{
    if ($first)
    {
        # skip first line
        $first = false;
    }
    else
    {
        print;
    }
}

and use this script as a filter:

cat myfile.txt | removefirstline.pl > myfile_2.txt
function cutline($filename,$line_no=-1) {

$strip_return=FALSE;

$data=file($filename);
$pipe=fopen($filename,'w');
$size=count($data);

if($line_no==-1) $skip=$size-1;
else $skip=$line_no-1;

for($line=0;$line<$size;$line++)
if($line!=$skip)
fputs($pipe,$data[$line]);
else
$strip_return=TRUE;

return $strip_return;
}

cutline('foo.txt',1); // deletes line 1 in foo.txt
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top