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

조회 수: 11 (최근 30일)
Lucy Cathwell
Lucy Cathwell 2019년 8월 21일
답변: the cyclist 2019년 8월 22일
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!

답변 (2개)

Image Analyst
Image Analyst 2019년 8월 21일
편집: Image Analyst 2019년 8월 22일
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 2019년 8월 22일
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.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by