How to find and store specific parameters in text file.
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
KSSV
el 10 de Oct. de 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 comentarios
KSSV
el 11 de Oct. de 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
el 10 de Oct. de 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 comentarios
Stephen23
el 11 de Oct. de 2018
Editada: Stephen23
el 11 de Oct. de 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.
Ver también
Categorías
Más información sobre Entering Commands en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!