Merge specific .txt files depending on the prefix.

2 views (last 30 days)
Hello,
I have multiple .txt files with names like:
M1_mR1.txt, M1_mR2.txt,.... M1_mr100.txt
AND
M2_mr2.txt,M2_mR2.txt,..., M2_mR100.txt.
I would like to merge into one file all the files that have the prefix "M1_", and after that I would like to merge into one file all the files that have the prefix "M2_".
If I want to merge files with different suffix I am using these commads:
txtFiles = dir('mR*.txt') ; % get the text files in the present folder
N = length(txtFiles) ; % Total number of text files
iwant = cell(N,1) ; % initlaize the data required
% loop for each file
for i = 1:N
thisFile = txtFiles(i).name ;
iwant{i} = importdata(thisFile) ; % read data of the text file
end
iwant = cell2mat(iwant) ;
outFile = strcat('finalR.txt') ;
dlmwrite(outFile,iwant,'delimiter','\t')
How could I solve my problem, by modifying my code?

Answers (1)

dpb
dpb on 4 Jul 2020
Just iterate over the prefix of interest...
indx=1; % initial prefix number
fileString="M"+indx+"_*.txt"; % use strings for convenience
d=dir(fileString); % return first search
while ~isempty(d) % indefinite loop construct for unknown number
for i = 1:numel(d) % loop over the returned struct
data{i}=importdata(d(i).name);
end
indx=indx+1; % try next set in sequence
fileString="M"+indx+"_*.txt";
d=dir(fileString);
end
data=cell2mat(data);
outFile = strcat('finalR.txt');
dlmwrite(outFile,data,'delimiter','\t')
should be reasonable start point. Air code, not tested...

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!