How to loop multi-line with data text?
1 view (last 30 days)
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.

Accepted Answer
Mathieu NOE
on 20 Apr 2022
hello again
try this code - does not require readlines
line_index will give you which line contains the searched string
filename = 'EX.txt';
str = "Printing Done";
[lines,count,line_index] = myfunction_read(filename,str)
%%%%%%% functions %%%%%%%%%
function lines = my_readlines(filename)
% work around for earlier matlab releases (not having readlines)
lines = regexp(fileread(filename), '\r?\n', 'split');
if isempty(lines{end}); lines(end) = []; end %end of file correction
end
%%%%%%%%%%%%%%%%%%%%%%%%%
function [lines,count,line_index] = myfunction_read(filename,str)
lines = my_readlines(filename);
% init data
count = 0;
for ci = 1:numel(lines)
ll = lines(ci);
if contains(ll,str) %
count = count+1;
line_index(count) = ci;
end
end
end
1 Comment
Mathieu NOE
on 20 Apr 2022
if you need to display the corresponding lines, it's fairly easy :
selected_lines = lines(line_index)'
selected_lines =
5×1 cell array
{'2021-3-31 7:23:46 504 [INFO] Print Job 6704654239889586 Status Done: Printing Done'}
{'2021-3-31 7:24:3 486 [INFO] Print Job 6704654422370495 Status Done: Printing Done' }
{'2021-3-31 7:25:6 409 [INFO] Print Job 6704655051285743 Status Done: Printing Done' }
{'2021-3-31 7:27:7 256 [INFO] Print Job 6704656259440377 Status Done: Printing Done' }
{'2021-3-31 7:27:18 300 [INFO] Print Job 6704656372070258 Status Done: Printing Done'}
More Answers (1)
Voss
on 20 Apr 2022
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{:})
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!