Reading text file from a certain string onwards in matlab -
[11/01/15 - 17:50] refa,2,5,600, [11/01/15 - 17:52] refb,1,3, [11/01/15 - 17:54] refa,2,10,1200, [11/01/15 - 17:55] refb,1,6,
i have text file of several lines of above format. how can start reading text file refa , store 2,5,600 in matlab?
you can regular expressions. find parts of string begin [
, end ]
, replace them null string, or ''
. can done regexprep
.
as such, read in entire text file first, eliminate portions don't need. assuming text file in file called text.txt
, this:
fid = fopen('text.txt', 'r'); out = textscan(fid, '%s', 'delimiter', '\n'); out = regexprep(out{1}, '\s*\[.*\]\s*', '');
the first line of code opens file reading. next part reads in each line of text cell array, output 1 element nested cell array, each cell within single line of text file. last line accesses single nested element , finds portion of string there white space, beings [
character, has bunch of characters inside, ends ]
character , again white space after that. find portions of text, , replace them null string. gives portion of text looking for.
by placing example text in file called text.txt
, get:
out = 'refa,2,5,600,' 'refb,1,3,' 'refa,2,10,1200,' 'refb,1,6,'
now if want numerical values, can use indexing:
out = cellfun(@(x) x(6:end-1), out, 'uni', 0);
now, work code (in comments), try this:
fileid = fopen('stack.txt'); d = textscan(fileid, '%s', 'delimiter', '\n'); fclose(fileid); d = regexprep(d{1}, '\s*\[.*\]\s*', ''); d = cellfun(@(x) x(6:end-1), d, 'uni', 0); %// extract out numbers numbers = regexp(d, '(\d+)*', 'tokens'); %// @ lines have 3 numbers idx = cellfun(@numel, numbers) == 3; %// extract out lines numbers_extract = numbers(idx); %// convert string numbers refa.pkttype = cellfun(@(x) x(1), numbers_extract); refa.datalength = cellfun(@(x) x(2), numbers_extract); refa.ticks = cellfun(@(x) x(3), numbers_extract);
Comments
Post a Comment