전체 텍스트 파일에 메모리를 할당하지 않고 텍스트 파일에서 첫 번째 줄 제거

StackOverflow https://stackoverflow.com/questions/1802757

  •  05-07-2019
  •  | 
  •  

문제

매우 큰 텍스트 파일이 있으며 파일 상단에서 한 줄을 제거하면됩니다. 이상적으로는 PHP에서 수행되지만 모든 UNIX 명령은 잘 작동합니다. 나는 n에 도달 할 때까지 파일의 시작 부분을 통해 스트리밍 할 수 있다고 생각하지만 어떻게 그렇게하는지 잘 모르겠습니다.

고마워, Matt Mueller

도움이 되었습니까?

해결책

sed -i -e '1d' file 당신이 원하는 것을 할 것입니다.

  • -i "현장"을 나타냅니다.
  • -e "이 표현 평가"를 의미합니다.
  • '1d' 의미, 첫 번째 줄을 삭제하십시오

다른 팁

*nix에서 다양한 도구를 사용할 수 있습니다. 150 만 행 이상의 파일의 다른 방법을 비교합니다.

$ 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

파일이 평평한 경우 사용할 수 있습니다 sed '1d' file > newfile

GNU Coreutils의 꼬리를 가정합니다.

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

양수가있는 꼬리는 N-th line으로 시작하는 모든 것을 출력합니다.

다음 명령을 시도하십시오.

sed -n '2,$p' file

파일이 얼마나 큰지 모르겠지만 시도 했습니까? awk 'NR > 1' {print} ?

나는 Perl에서 약간 녹슬었지만 이것은 트릭을 할 수 있습니다.

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

이 스크립트를 필터로 사용하십시오.

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top