MATLAB Answers

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

20 views (last 30 days)
Jonas Kuhn
Jonas Kuhn on 13 Feb 2020
Edited: Stephen Cobeldick on 14 Feb 2020
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!


Sign in to comment.

Accepted Answer

Murugan C
Murugan C on 13 Feb 2020
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')
file_name = [get_folder(i1).name '_'];
copyfile([dir1 '\'], [pwd '\' outputFolder, '\',file_name]);


Stephen Cobeldick
Stephen Cobeldick on 13 Feb 2020
Rather than using a hard-coded separator character like this:
dir1 = [pwd, '\', get_folder(i1).name,'\', common_folder1, '\', common_folder2 ];
it is strongly recommended to use simpler and more robust fullfile:
dir1 = fullfile(pwd, get_folder(i1).name, common_folder1, common_folder2);

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!