Merge specific .txt files depending on the prefix.

조회 수: 1 (최근 30일)
Ivan Mich
Ivan Mich 2020년 7월 4일
댓글: dpb 2020년 7월 4일
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?

답변 (1개)

dpb
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...
  댓글 수: 2
Ivan Mich
Ivan Mich 2020년 7월 4일
I am afriad but it's no use ...
dpb
dpb 2020년 7월 4일
And why would that be, pray tell...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by