Merge specific .txt files depending on the prefix.

2 Ansichten (letzte 30 Tage)
Ivan Mich
Ivan Mich am 4 Jul. 2020
Kommentiert: dpb am 4 Jul. 2020
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?

Antworten (1)

dpb
dpb am 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...
  2 Kommentare
Ivan Mich
Ivan Mich am 4 Jul. 2020
I am afriad but it's no use ...
dpb
dpb am 4 Jul. 2020
And why would that be, pray tell...

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by