How to find and store specific parameters in text file.
12 views (last 30 days)
Show older comments
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 Comments
Answers (2)
KSSV
on 10 Oct 2018
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 Comments
KSSV
on 11 Oct 2018
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
on 10 Oct 2018
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 Comments
Stephen23
on 11 Oct 2018
Edited: Stephen23
on 11 Oct 2018
"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.
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!