Merge specific .txt files depending on the prefix.
조회 수: 1 (최근 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!