필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to store lines in a text file based on preceding text

조회 수: 1 (최근 30일)
Daniel Ringle
Daniel Ringle 2019년 4월 29일
마감: MATLAB Answer Bot 2021년 8월 20일
Hello,
I am trying to figure out how to capture and store every line in a text file that directly follows a line containing certain words. Basically I have large text files containing millions of lines of residuals (from a numerical simulation) and I am only concerned with the lowest values. The lowest values are always preceded by a sentence that starts with the words “time step”.
I have used Matlab a bit for mathematics (solving ODE’s, numerical optimization etc...) but never anything like this and am at a loss.
Any help much appreciated!

답변 (2개)

Bob Thompson
Bob Thompson 2019년 4월 29일
편집: Bob Thompson 2019년 4월 29일
There are a couple of methods for doing this. Let me know if you have questions.
fid = fopen('mytextfile.txt');
line = fgetl(fid);
count = 1;
data = '';
while ~isnumeric(line)
if length(line) > 5 & strcmp(line(1:9),'time step')
line = fgetl(fid);
count = count + 1;
data = line; % This command is really incomplete. YOu need to index data, but how you handle the data itself is largely dependent on the type of data you are using. Look into str2num or cells if necessary.
else
line = fgetl(fid);
count = count + 1;
end
end
This is the line by line search. It is the classic reliable method.
text = fileread('mytextfile.txt');
text = regexp(text,'\n','split');
rows = strfind([text{:}],'time step');
data = cell2mat([text{rows+1}]); % cell2mat may not work because it's a character array. I don't remember off the top of my head. Should identify the correct rows though
This is the regexp method. It's a bit more complicated, but looks more concise.
You can use either method you feel comfortable with, but you will need to adapt either one of them to what you're doing. These will almost certainly not work with just a copy and paste.

Image Analyst
Image Analyst 2019년 4월 29일
Something like
% Open the file.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
while ischar(textLine)
% Print out what line we're operating on.
fprintf('%s\n', textLine);
if startsWith(textLine, 'time step')
% Yay! We found out line with key words in it.
% Read the next line.
textLine = fgetl(fileID);
% do something with this line -- not sure what though. Maybe get numbers from it or something.
end
% Read the next line.
textLine = fgetl(fileID);
end
% All done reading all lines, so close the file.
fclose(fileID);
Adapt as needed.

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by