Extracting specific repeating lines of text after a heading using fgetl and textscan
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Vincent Scalfani
le 19 Juil 2016
Commenté : Vincent Scalfani
le 21 Juil 2016
Here is an example of the data I am working with. I would like to extract the line directly following each KEY tag. The files have many thousands of these, so I need to create a loop with textscan or something similar.
> <NAME>
mary
> <AGE>
30
> <KEY>
RDHQFKQIGNG
> <NAME>
john
> <AGE>
56
> <KEY>
JFJNNFNFKFNN
Desired result:
RDHQFKQIGNG
JFJNNFNFKFNN
Here is where I am at (adapted from a similar question in the past), the code does not seem to be moving the cursor, and instead works for the first one, and then grabs all data after it, instead of just the data following the KEY line.
f = fopen('data.txt', 'rt');
tline = fgetl(f);
while isempty(strfind(tline, '> <KEY>'))
if tline == -1
break;
end
line = fgetl(f);
end
if tline ~= -1
data = textscan(f,'%s','Delimiter','\r\n');
else
disp('not found');
end
fclose(f);
Thanks!
0 commentaires
Réponse acceptée
Stephen23
le 19 Juil 2016
>> str = fileread('temp1.txt');
>> C = regexp(str,'(?<=> <KEY>\s+)\S+','match')
C =
'RDHQFKQIGNG' 'JFJNNFNFKFNN'
Tested on this file:
3 commentaires
Stephen23
le 20 Juil 2016
Try this:
E = regexp(str,'^> <KEY>\s+\S+','match','lineanchors');
E = strtrim(strrep(E,'> <KEY>',''));
And have a play with this script:
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Text Files dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!