Merge .txt files with specific suffix

조회 수: 1 (최근 30일)
Ivan Mich
Ivan Mich 2020년 7월 31일
댓글: Mario Malic 2020년 8월 3일
Hello,
I have multiple .txt files with names like:
mR1_M1_D1.txt, mR2_M1_D1.txt,....mr100_ M1_D1.txt
mR1_M1_D2.txt, mR2_M1_D2.txt,....mr100_ M1_D2.txt
mR1_M2_D1.txt, mR2_M2_D1.txt,....mr100_ M2_D1.txt
AND
mR1_M2_D2.txt, mR2_M2_D2.txt,....mr100_ M2_D2.txt.
All the files I have mentioned there are in a folder. I would like to group all this files into 4 groups depending on the semifinal and final suffix. the semifinal suffix is M1 and M2 and the final suffix is D1 and D2.
So I want one group with all the files with suffix : M1D1.txt
one group with all the files with suffix : M1D2.txt
one group with all the files with suffix : M2D1.txt
one group with all the files with suffix : M2D2.txt
Notice: These files have 4 columns and 1 line ( I am uploading a format)
could you help me?
I think that I have to modify this script , but I do not know how:
clc
clear
% to read files starting with M1
txtFiles = dir("mR*.txt") ;
N = length(txtFiles) ;
A = zeros(N,4) ;
for i = 1:N
a = importdata(txtFiles(i).name) ;
A(i,:) = a ;
end
writematrix(A,'RESULTS.txt','Delimiter','tab');
  댓글 수: 1
Mario Malic
Mario Malic 2020년 8월 3일
If your files are created in the order that you want to group them and know how many you have, you can find all files that have the "mR" prefix and sort by the date. You would get 400 rows with their names from which 1-101 would be mR1 and so on. If not, then you can just sort them by the date and every 4th row will belong to the same mRx.

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

답변 (1개)

jonas
jonas 2020년 7월 31일
Could do something like this if you have a small number of "groups". For a large number of groups, I would suggest just extracting the identifier and then use findgroups() or unique() to group.
% to read files starting with M1
txtFiles = dir("mR*.txt") ;
names = {txtFiles.name}'
groups = {'M1_D1';'M1_D2';'M2_D1';'M2_D2'};
%loop over groups
for j = 1:numel(groups)
id = contains(names,groups{j});
names_sub = names(id)
if isempty(names_sub)
continue
end
N = length(names_sub);
A = zeros(N,4) ;
%loops over files in each group
for i = 1:N
a = importdata(names_sub{i}) ;
A(i,:) = a ;
end
%save file
fname_out = sprintf('Results_%s.txt',groups{j})
writematrix(A,fname_out,'Delimiter','tab');
end

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by