using textscan to find the rest of the line after the specific expression...

9 visualizaciones (últimos 30 días)
file = uigetfile('*.txt','Select the text file to parse');
fid=fopen(file)
text=fileread(file)
I have a really long complicated text file that I want to parse. It is really long and is a list of lines. There are no comma delimiters, but the machine name that I am looking for is always at the end of the line ... like
121212323 : Machine Name = roboDog
121222323 : Machine IOS = Android
The code above was my attempt to desplay the lines which contained the keyword. It wouldn't work, but I would ideally like each Machine Name to be stored in a vector like machineName={'roboDog' ; 'roboCat'}
Thanks!

Respuestas (2)

Image Analyst
Image Analyst el 21 de Ag. de 2019
Editada: Image Analyst el 22 de Ag. de 2019
Try this:
% Open the file.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
machineName = {}; % Initialize to null
while ischar(textLine)
% Print out what line we're operating on so we can see it.
fprintf('%s\n', textLine);
if contains(textLine, ' : Machine Name', 'IgnoreCase', true)
% Line of text included Machine. Get stuff after the equal sign and strip off any leading and trailing spaces.
equalLocation = strfind(textLine, '= ')
machineName{end+1} = strtrim(textLine(equalLocation + 1 : end))
end
% Read the next line.
textLine = fgetl(fileID);
end
% All done reading all lines, so close the file.
fclose(fileID);
machineName is your cell array of strings.

the cyclist
the cyclist el 22 de Ag. de 2019
The code I posted in your other question ...
text=fileread(fileName);
expr='(?<=Name = )\w*';
machineName=regexp(text, expr,'match');
gives the same result in machineName as Image Analyst's answer, in a couple simple tests.

Community Treasure Hunt

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

Start Hunting!

Translated by