How to loop multi-line with data text?
显示 更早的评论
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 个评论
Mathieu NOE
2022-4-20
hi
try readlines
Mathieu NOE
2022-4-20
seems I have already seen this log file in another post ....
was the provided solution finally not good enough ?
Peter Fang
2022-4-20
@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
2022-4-20
采纳的回答
更多回答(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 个评论
Peter Fang
2022-4-20
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
2022-4-21
类别
在 帮助中心 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!