How to find and store specific parameters in text file.
1 次查看(过去 30 天)
显示 更早的评论
I'm having few text files with both strings and values that are not organized properly and without a consistent patterns. I need to retrieve the Serial number in each text file. What types of function can I used to solve this problem? **The attachment is just a sample of the text file, the content arrangement sequence are different in the other files.
0 个评论
回答(2 个)
KSSV
2018-10-10
fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
idx = contains(S,'Serial Number');
L = S(idx) ;
L = strsplit(L{1}) ;
N = str2double(L{3})
2 个评论
KSSV
2018-10-11
contains is introduced in 2016b..try this:
fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
idx = strfind(S, 'Serial Number');
idx = find(not(cellfun('isempty', idx)));
L = S(idx) ;
L = strsplit(L{1}) ;
N = str2double(L{3})
Stephen23
2018-10-10
One very simple solution would be to read the whole file and use a regular expression. Something like this:
D = 'directory where the files are';
S = dir(fullfile(D,'*.txt'));
C = cell(1,numel(S));
for k = 1:numel(S)
T = fileread(fullfile(D,S(k).name));
C{k} = regexp(T,'(?<=^Serial Number )\d+','lineanchors','match');
end
V = str2double(C)
2 个评论
Stephen23
2018-10-11
编辑:Stephen23
2018-10-11
"Can you explain about this phrase'(?<=^Serial Number )\d+', I don't understand why must it represented in this form"
That is the regular expression that matches |Serial Number | at the start of a line, and returns the number that immediately follows. You can learn about regular expressions here:
"And when I run the code V shows NaN."
It worked when I tried it on your sample file. Please upload an actual data file.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!