Info
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
How to store lines in a text file based on preceding text
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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!
0 Commenti
Risposte (2)
Bob Thompson
il 29 Apr 2019
Modificato: Bob Thompson
il 29 Apr 2019
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.
0 Commenti
Image Analyst
il 29 Apr 2019
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.
0 Commenti
Questa domanda è chiusa.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!