Splitting a file into multiple files and need to generate file names from the individual files
3 views (last 30 days)
Show older comments
Erik Sarnello
on 28 Jun 2021
Commented: Erik Sarnello
on 30 Jun 2021
I am using the code below to split a large file into many files. I am splitting at the defined character "Z". The code works as intended but as of now I just have my file names as 'Data 1' 'Data 2' and so on. I have the variable 'destnames' storing the first line of the file and I would like to pull a segment from there to be the file name. Data example and code below
For example I would like to make 'S5C_00096 the file name for this file (Below is example of what is being stored in 'destnames', which is currenly not being used in the code)
' S5C_00096_00001.tif 5.0000 5.0300 11.4993 1700497.970037 34462.970037 999814.344062 0.101 -0.100 0.000 0.000 26.438 0.000 1.000 Sat Jun 19 09:01:03 2021 1624111263.0071930885'
Code
wholefile = fileread('C:\Location\test.txt');
splitfiles = regexp(wholefile, 'Z[^Z]+', 'match');
destnames = regexp(splitfiles, '(?<=Z)[^\r\n]+', 'match', 'once');
for fileidx = 1:numel(splitfiles)
fid = fopen(sprintf('Data%2d.txt', fileidx), 'w');
fwrite(fid, splitfiles{fileidx});
fclose(fid);
end
3 Comments
Accepted Answer
Stephen23
on 30 Jun 2021
Edited: Stephen23
on 30 Jun 2021
whf = fileread('./testsplit.txt');
spl = regexp(whf,'\s+#Z\s+','split'); % more robust than just 'Z'
for k = 2:numel(spl) % first split text is empty
fnm = regexp(spl{k},'^\S+(?=_\d+\.tif)','match','once');
fnm = sprintf('%s.txt',fnm);
fid = fopen(fullfile('.',fnm), 'w');
fprintf(fid,'#Z ');
fwrite(fid, spl{k});
fclose(fid);
end
Checking folder content after running the code:
dir *.txt
Checking the content of the first file:
type S5C_00096.txt
More Answers (0)
See Also
Categories
Find more on Text Data Preparation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!