How to loop multi-line with data text?
Mostrar comentarios más antiguos
Hi everyone.
I have a question: How to loop muilti-line with data text? (The image describes the data below)
Please help me.
Thank you.

5 comentarios
Mathieu NOE
el 20 de Abr. de 2022
hi
try readlines
Mathieu NOE
el 20 de Abr. de 2022
seems I have already seen this log file in another post ....
was the provided solution finally not good enough ?
Peter Fang
el 20 de Abr. de 2022
@Peter Fang Why use a for loop at all? Just read the whole file at once:
fid = fopen('EX.txt');
data = fread(fid,'*char').';
fclose(fid);
disp(data);
Peter Fang
el 20 de Abr. de 2022
Respuesta aceptada
Más respuestas (1)
You can read the file in one fell swoop, then break the contents into individual lines, and retrieve the dates/times from lines where 'Printing Done' appears:
% read the entire file
fid = fopen('EX.txt');
data = fread(fid,'*char').';
fclose(fid);
% cell array C, with each element containing one line of text
C = strsplit(data,newline()).'
% keep only lines saying 'Printing Done'
C = C(contains(C,'Printing Done'))
% grab the dates/times from those lines
dates = regexp(C,'(\d+-\d+-\d+ \d+:\d+:\d+)','tokens','once');
dates = vertcat(dates{:})
3 comentarios
Peter Fang
el 20 de Abr. de 2022
Sure, you can do this:
fid = fopen('output.txt','w');
fprintf('%s\n',dates{:});
fclose(fid);
Demonstrating with the input txt file from before:
% reading input file
fid = fopen('EX.txt');
data = fread(fid,'*char').';
fclose(fid);
% parsing dates of 'Printing Done'
C = strsplit(data,newline()).';
dates = regexp(C(contains(C,'Printing Done')),'(\d+-\d+-\d+ \d+:\d+:\d+)','tokens','once');
dates = vertcat(dates{:});
% writing dates to output file
fid = fopen('output.txt','w');
fprintf(fid,'%s\n',dates{:});
fclose(fid);
% checking the output file
type('output.txt');
Peter Fang
el 21 de Abr. de 2022
Categorías
Más información sobre Data Import and Export en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!