How to split text files into many text files?
4 views (last 30 days)
Show older comments
Hi everyone. Can anyone help us to split the data into many files. The example data is attached.
This is how the data look like..
Lat: 6.4931, Lon: 99.6067, Parameter: z(m) <--This is the start line
Depth (m): 22.45
Constituents included: m2 s2 k1 o1
Time start: 00:00, 1. 1.1993
Time step (min): 60.00
Time Series length (hours):236664
01-Jan-1993 00:00:00 -0.0946
01-Jan-1993 01:00:00 -0.3369
01-Jan-1993 02:00:00 -0.5110
... More Data
31-Dec-1993 23:59:59 -1.1673 <-- This is the last line
Lat: 6.3933, Lon: 99.6067, Parameter: z(m) <--- Another start line for different coordinate
Depth (m): 30.74
Constituents included: m2 s2 k1 o1
Time start: 00:00, 1. 1.1993
Time step (min): 60.00
Time Series length (hours):236664
01-Jan-1993 00:00:00 -0.1017
01-Jan-1993 01:00:00 -0.3324
01-Jan-1993 02:00:00 -0.4965
... More Data
31-Dec-1993 23:59:59 -1.1284 <--Another last line
0 Comments
Accepted Answer
Rik
on 25 Aug 2020
Edited: Rik
on 25 Aug 2020
The code below assumes each file ends with an empty line. You could also search for 'Lat:' instead to determine the beginning of a new file.
data=readfile('https://www.mathworks.com/matlabcentral/answers/uploaded_files/351353/Example.txt');
lastlineoffile=find(cellfun('isempty',data));
lastlineoffile=[0;unique([lastlineoffile;numel(data)])];%add last line just to make sure
for n=1:(numel(lastlineoffile)-1)
currentfile=data((lastlineoffile(n)+1):lastlineoffile(n+1));
fid=fopen(sprintf('aa__file%03d.txt',n),'w');
fprintf(fid,'%s\n',currentfile{:});
fclose(fid);
end
3 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!