Borrar filtros
Borrar filtros

Delete lines from text file

17 visualizaciones (últimos 30 días)
Sergio
Sergio el 29 de Ag. de 2013
Comentada: Josh Murman el 26 de Mzo. de 2020
How can I delete all the lines form a text file after the line number x and store it in another test file?

Respuesta aceptada

Image Analyst
Image Analyst el 29 de Ag. de 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 comentarios
Sergio
Sergio el 29 de Ag. de 2013
this worked perfect! Thank you!
Josh Murman
Josh Murman el 26 de Mzo. de 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);

Iniciar sesión para comentar.

Más respuestas (1)

dpb
dpb el 29 de Ag. de 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'.

Categorías

Más información sobre Large Files and Big Data en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by