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

10 ビュー (過去 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!
  1 件のコメント
the cyclist
the cyclist 2019 年 8 月 21 日
Isn't this identical to your question here? Or did I miss something subtle?

サインインしてコメントする。

回答 (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 Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by