How can I copy files from multiple subfolders into a new folder and rename them while doing so?

15 vues (au cours des 30 derniers jours)
Hi, I'm having a few problems figuring this out and I hope someone can help me:
I have multiple folders with differnet names (i.e. 1_5, 1_10 etc.) and each of them contains a subfolder (Erg), which contains another subfolder named DV.
In this last subfolder there is a specific file which always has the same name (solution_1).
Now I want to copy all solution_1 files in a newly created soltution folder and add a prefix so that each file has the name of the "masterfolder" in front of it.
Like this: 1_5_solution_1, 1_10_solution_1 etc.
I tried to visualize the folder structure below:
- 1_5
- Erg
- DV
- solution_1.txt
- 1_10
- Erg
- DV
- solution_1.txt
- solutions
- 1_5_solution_1.txt
- 1_10_solution_1.txt
I hope it is understandable and someone can help me.
Have a great day and thank you in advance!

Réponse acceptée

Murugan C
Murugan C le 13 Fév 2020
hi,
if your all folder's are same structure. pl use this code.
common_folder1 = 'Erg';
common_folder2 = 'DV';
outputFolder = 'solutions';
get_folder = dir;
for i1 = 3 : length(get_folder)
if isdir(get_folder(i1).name)
dir1 = [pwd, '\', get_folder(i1).name,'\', common_folder1, '\', common_folder2 ];
d = dir(fullfile(dir1, '*.txt'));
if ~isempty(d)
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
file_name = [get_folder(i1).name '_' d.name];
copyfile([dir1 '\' d.name], [pwd '\' outputFolder, '\',file_name]);
end
end
end
  3 commentaires
Jonas Kuhn
Jonas Kuhn le 13 Fév 2020
Thank you very much! Both of you! This works perfectly :)
Murugan C
Murugan C le 14 Fév 2020
Yes Stephen, I will do hereafter. Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by