Merge .txt files with specific suffix

4 Ansichten (letzte 30 Tage)
Ivan Mich
Ivan Mich am 31 Jul. 2020
Kommentiert: Mario Malic am 3 Aug. 2020
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
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:
% 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 ;
  1 Kommentar
Mario Malic
Mario Malic am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

jonas am 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 = {}'
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)
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 ;
%save file
fname_out = sprintf('Results_%s.txt',groups{j})

Community Treasure Hunt

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

Start Hunting!

Translated by