MATLAB: Parsing a Large Text File into Sections

getlparsetext;

I have a large text file as below:
Run Lat Long Time
1 32 32 34
1 23 22 21
2 23 12 11
2 11 11 11
2 33 11 12
up to 10 runs etc.
So I'm trying to break up each section in the file: section 1, section 2, etc and write it to 10 different text files. File 1 will have data from Run 1. File 2 will have data from Run 2.
Thanks,
Amanda

Best Answer

Hi Amanda,
This should work for you. It just reads the input file one line at a time and prints that line to an output file. If it hits a new "section", it makes a new output file named by that section.
fidIn = fopen('inputFile.txt','r');
oldFirstChars = 'somethingtostart';
fidOut = [];
while 1
tline = fgetl(fidIn);
if ~ischar(tline), break, end % Handle the end of the input file
% Get the string up to the first space
newFirstChars = regexp(tline, '\d+','match','once');
% If it's a new "section", make a new file
if ~strcmp(oldFirstChars, newFirstChars)
if ~isempty(fidOut)
% Close the old file first
fclose(fidOut);
end
fidOut = fopen(['outputFile' newFirstChars '.txt'],'w');
oldFirstChars = newFirstChars;
end
% Just print out the line that we just read to the output file
fprintf(fidOut, '%s\r\n',tline);
end
% Clean up any open files
fclose(fidIn);
fclose(fidOut);
Related Question