Delete lines from text file

14 次查看(过去 30 天)
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