How to loop multi-line with data text?
Show older comments
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 Comments
Mathieu NOE
on 20 Apr 2022
hi
try readlines
Mathieu NOE
on 20 Apr 2022
seems I have already seen this log file in another post ....
was the provided solution finally not good enough ?
Peter Fang
on 20 Apr 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
on 20 Apr 2022
Accepted Answer
More Answers (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 Comments
Peter Fang
on 20 Apr 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
on 21 Apr 2022
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!