Reading text file and searching for specific lines

1 view (last 30 days)
Hello,
I would like to ask you to help with reading and finding correct lines from given text file. Two categories of lines are in the following document: "Cable" and "Pipe" and I woud like to find lines of numbers below. Problem is that there are 4 lines of numbers for "Cable" and 26 number lines for first "Pipe" but it can be different. Could you suggest reliable way of finding those lines?
Best regards
Michal
  3 Comments
dpb
dpb on 9 May 2022
Edited: dpb on 9 May 2022
Well, we can't comment/correct/suggest improvements on code we can't see....attach your work and let somebody have a whack at it... :)
"... but how to find its end if length varies?"
That's the point made in the above comment -- the length is given for you in the eblock line it appears; and it's a fixed number of lines past the header, so read the length from that line and you've got it.
Alternatively, each section ends with a record containing only a "-1" so you can certainly just scan until you find it as well. Both of those could, in fact, be vectorized.

Sign in to comment.

Accepted Answer

dpb
dpb on 9 May 2022
D=readlines('Full_TableX.txt'); % read as string array
ixP1=find(contains(D,'Pipe')); % find the pipe sections
nP=str2double(extractAfter(D(ixP1+2),',,')); % read the number lines
for i=1:numel(ixP1) % process each section in turn
Pipe{i}=str2double(split(strtrim(D(ixP1(1)+4:ixP1(1)+4+nP(1)-1))));
end
will return you a cell array of the Pipe data sections -- it shouldn't be hard to figure out the Cable... :)
In fact, the above is generic for either; turn it into a function and pass the input data and search string and you're done.
One could amplify to get the component ID number for identification, etc., ...

More Answers (1)

Image Analyst
Image Analyst on 9 May 2022
Try this:
% Open the file for reading in text mode.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
% Print out what line we're operating on.
fprintf('%s\n', textLine);
% See if the line has 'Cable' in it.
if contains(textLine, 'Cable', 'IgnoreCase', true)
% It contains Cable.
end
% See if the line has 'Pipe' in it.
if contains(textLine, 'Pipe', 'IgnoreCase', true)
% It contains Pipe.
end
% Read the next line.
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
% All done reading all lines, so close the file.
fclose(fileID);
Adapt as needed. When you find the lines you're looking for, do something, such as saving the line number, transfer the line to another text file, or whatever you want to do.

Community Treasure Hunt

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

Start Hunting!