Merge specific .txt files depending on the prefix.
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
dpb
2020-7-4
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...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!