Merge .txt files with specific suffix

1 view (last 30 days)
Ivan Mich
Ivan Mich on 31 Jul 2020
Commented: Mario Malic on 3 Aug 2020
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 Comment
Mario Malic
Mario Malic on 3 Aug 2020
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.

Sign in to comment.

Answers (1)

jonas
jonas on 31 Jul 2020
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

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!