필터 지우기
필터 지우기

Delete lines from text file

조회 수: 17 (최근 30일)
Sergio
Sergio 2013년 8월 29일
댓글: Josh Murman 2020년 3월 26일
How can I delete all the lines form a text file after the line number x and store it in another test file?

채택된 답변

Image Analyst
Image Analyst 2013년 8월 29일
As shown in the help:
fid = fopen('fgetl.m');
tline = fgetl(fid);
while ischar(tline)
disp(tline)
tline = fgetl(fid);
end
fclose(fid);
Now just modify that to open 2 files, and add a line counter then break after you've transferred x of them (untested)
fin = fopen('input.txt');
fout = fopen('output.txt', 'wt');
tline = fgetl(fin);
count = 0;
while ischar(tline) && count < x
disp(tline)
tline = fgetl(fin);
if ischar(tline)
fprintf(fout, '%s\n', tline);
end
count = count + 1;
end
fclose(fin);
fclose(fout);
  댓글 수: 2
Sergio
Sergio 2013년 8월 29일
this worked perfect! Thank you!
Josh Murman
Josh Murman 2020년 3월 26일
Add ~strcmp(tline,'Expected Line Text to Remove') to the if statement if you would like to remove a line with that string. Also move the fgetl function in the while loop so the first line isn't skipped.
fin = fopen('input.txt');
fout = fopen('output.txt', 'wt');
tline = fgetl(fin);
while ischar(tline)
if ~strcmp(tline,'Expected Line Text to Remove') && ischar(tline)
fprintf(fout, '%s\n', tline);
end
tline = fgetl(fin);
count = count + 1;
end
fclose(fin);
fclose(fout);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2013년 8월 29일
Read line 1:x from 1 and copy to the second. Close the second. Done.
Alternatively, rather than line-by-line, read the whole file if it's small enough to fit in memory relatively easily and if x is a sizable fraction of the total number of lines. Then just save data(1:x,:) to the new file.
That's the thing about sequential files---they're, well, 'sequential'.

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by