필터 지우기
필터 지우기

Pulling out a number and a date + time from text file after specific lines

조회 수: 1 (최근 30일)
Hello all,
I have the following two lines in my text file:
Time of Interval 0: 03/03/18 18:14:02
Interval: 0.02 sec
First off, how can I pull out the number after "Interval:" ?
Secondly, how can I do the same for the date and time after "Time of Interval 0:" ?
The number and the date vary from file to file, but the text preceding them is always the same. I need a solution that works in every situation.
Thanks in advance!

채택된 답변

Bob Thompson
Bob Thompson 2019년 6월 27일
The most reliable way that I know of to get this is by using fgetl.
file = fopen('mytextfile.txt'); % Access the file
line = fgetl(file); % Read first line
c = 1; % Record the line number for debugging purposes
while ~isnumeric(line) & ~strcmp(line(1:16),'Time of Interval') % Check for desired line, or end of file
line = fgetl(file); % Read next line
c = c + 1; % Advance line count
end
parts = strsplit(line,': ');
number = str2num(parts{1}(18:end));
dt = datetime(parts{2});
There may be some thing syou need to tweak to make it personalized to your inputs, but that should work.
  댓글 수: 1
Heidi Mäkitalo
Heidi Mäkitalo 2019년 7월 2일
편집: Heidi Mäkitalo 2019년 7월 2일
For some reason Matlab complained about matrix dimensions being exceeded when I tried to use your code, don't know what that was about. This is how I ended up doing it:
Zero interval
function zinterval = FindZeroInterval(file)
opened_file = fopen(file,'rt');
zinterval = '';
while ~strncmpi(zinterval,'Time of Interval 0',18)
zinterval = fgetl(opened_file);
end
zinterval = datetime(zinterval(20:end), 'InputFormat','MM/dd/yy HH:mm:ss');
end
which gives
zinterval =
datetime
03-Mar-2018 18:14:02
and interval
function interval = FindInterval(file)
opened_file = fopen(file,'rt');
interval = '';
while ~strncmpi(interval,'Interval:',8)
interval = fgetl(opened_file);
end
interval = str2double(regexp(interval,'\d+[\.]?\d*','match','once'));
end
which gives
interval =
0.0200
So basically I looked after your answer but changed some things around. Thanks a lot for your help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by