reading data after a string
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I would like to read the data below the words 'Link Results'. What i would really like to know is how to get the line number in the text file that I'm trying to read that has 'Link Results'. After I get that I know how to read the data. so my question would be how to find that number.
Thanks!
3 个评论
Cedric
2013-10-27
And how does the table end? Is it the end of file or is there some other content afterwards?
采纳的回答
Cedric
2013-10-27
编辑:Cedric
2013-10-27
Here is one way, assuming that the block of data is the last content that you have in the file. If not, I can update the answer. As Walter is pointing out, we have to read the file from the beginning (here we read the full content) and match pattern(s). This solution does that using a a regular expression, which is quite concise, but you could implement a more basic loop which scans each line.
content = fileread( 'myFile.txt' ) ;
blocks = regexp( content, 'Link Results.*?Full.*?\-\s(.*)', 'tokens' ) ;
block = blocks{1}{1} ;
data = textscan( block, '%s %s %f %f %f %f' ) ;
After running this, you get..
>> data
data =
{3x1 cell} {3x1 cell} [3x1 double] [3x1 double] [3x1 double] [3x1 double]
>> data{1}
ans =
'SEP-29-2010'
'SEP-29-2010'
'SEP-29-2010'
>> data{2}
ans =
'00:15:00'
'00:30:00'
'00:45:00'
>> data{3}
ans =
0
0
0
etc. Then you can post-process this cell array to get e.g. a cell array of time stamps, and a numeric array of data..
timeStamps = arrayfun( @(r) [data{1}{r}, ' ', data{2}{r}], ...
1:numel(data{1}), 'UniformOutput', false ).' ;
dataNum = [data{3:end}] ;
which leads to:
>> timeStamps
timeStamps =
'SEP-29-2010 00:15:00'
'SEP-29-2010 00:30:00'
'SEP-29-2010 00:45:00'
>> dataNum
dataNum =
0 0 0 0
0 0 0 0
0 0 0 0
更多回答(1 个)
Walter Roberson
2013-10-27
There are no functions built into MATLAB, or to any of the operating systems that current MATLAB run on, that can tell you which line number of a file that you are positioned to. None of the operating systems supported have any inherent concept of "line number".
Therefore if you want to know which line number something is on, you need to start at the beginning of the file, read line by line, counting each as you go, until you find the pattern you are looking for.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Standard File Formats 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!