Merge specific text files
1 view (last 30 days)
Show older comments
I have a code that for each iteration creates specific files with names :
M1_mR1.txt,...,M1_mr100.txt, and
M2_mR1.txt,..., M2_mR100.txt.
After that I would like to merge all the files that Have prefix M1_.....txt into one file and all the files that Have prefix M2_.....txt into one file.
How could I do this?
3 Comments
Accepted Answer
Stephen23
on 6 Jul 2020
Edited: Stephen23
on 6 Jul 2020
You will need two loops, the outer loop for M1, M2, etc, and the inner loop for the files R1,R2,R3,...R100, e.g.:
D = 'path to the directroy where the files are saved';
Mn = 3; % number of groups.
Rn = 100; % number of files in each group.
for Mk = 1:Mn % M1, M2, ...
C = cell(1,Rn); % preallocate cell array for this group
for Rk = 1:Rn % R1, R2, ... R100
F = sprintf('M%u_mR%u.txt',Mk,Rk);
C{Rk} = dlmread(fullfile(D,F))
end
M = vertcat(C{:}); % create one matrix from entire group
F = sprintf('M%u_ALL.txt',Mk);
dlmwrite(F,M) % save
end
Of course you do not have to use dlmread and dlmwrite: you can trivially change the file importing/exporting functions for something more suitable, or that you have a preference for, or that you think is fancier.
Note that this answer will actually concatenate the file data in the order R1,R2,R3,...R100.
0 Comments
More Answers (1)
KSSV
on 6 Jul 2020
% to read files starting with M1
txtFiles = dir("M1*.txt") ;
N = length(txtFiles) ;
A = zeros(N,4) ;
for i = 1:N
a = importdata(txtFiles(i).name) ;
A(i,:) = a ;
end
4 Comments
Stephen23
on 6 Jul 2020
Edited: Stephen23
on 6 Jul 2020
Note that this answer will concatenate the file data in this order:
M1_mR1.txt
M1_mR10.txt
M1_mR100.txt
M1_mR11.txt
M1_mR12.txt
M1_mR13.txt
M1_mR14.txt
M1_mR15.txt
M1_mR16.txt
M1_mR17.txt
M1_mR18.txt
M1_mR19.txt
M1_mR2.txt
M1_mR20.txt
M1_mR21.txt
M1_mR22.txt
...
M1_mR89.txt
M1_mR9.txt
M1_mR90.txt
M1_mR91.txt
M1_mR92.txt
M1_mR93.txt
M1_mR94.txt
M1_mR95.txt
M1_mR96.txt
M1_mR97.txt
M1_mR98.txt
M1_mR99.txt
which is unlikely to be very useful for further analysis.
To import the files in order 1,2,3,...100 you will either need to sort the filenames taking into account the number value (e.g. using an alphanumeric sort) or generate the filenames yourself (e.g. using sprintf).
See Also
Categories
Find more on Structures 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!