Azzera filtri
Azzera filtri

Delete lines from text file

17 visualizzazioni (ultimi 30 giorni)
Sergio
Sergio il 29 Ago 2013
Commentato: Josh Murman il 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?

Risposta accettata

Image Analyst
Image Analyst il 29 Ago 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 Commenti
Sergio
Sergio il 29 Ago 2013
this worked perfect! Thank you!
Josh Murman
Josh Murman il 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);

Accedi per commentare.

Più risposte (1)

dpb
dpb il 29 Ago 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'.

Categorie

Scopri di più su Large Files and Big Data in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by