Delete lines from text file

22 views (last 30 days)
Sergio
Sergio on 29 Aug 2013
Commented: Josh Murman on 26 Mar 2020
How can I delete all the lines form a text file after the line number x and store it in another test file?

Accepted Answer

Image Analyst
Image Analyst on 29 Aug 2013
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 Comments
Sergio
Sergio on 29 Aug 2013
this worked perfect! Thank you!
Josh Murman
Josh Murman on 26 Mar 2020
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);

Sign in to comment.

More Answers (1)

dpb
dpb on 29 Aug 2013
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'.

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!