MATLAB Answers

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

23 ビュー (過去 30 日間)
Jonas Kuhn
Jonas Kuhn 2020 年 2 月 13 日
編集済み: Stephen Cobeldick 2020 年 2 月 14 日
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!

  0 件のコメント



Murugan C
Murugan C 2020 年 2 月 13 日
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]);

  3 件のコメント

Stephen Cobeldick
Stephen Cobeldick 2020 年 2 月 13 日
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);
Jonas Kuhn
Jonas Kuhn 2020 年 2 月 13 日
Thank you very much! Both of you! This works perfectly :)
Murugan C
Murugan C 2020 年 2 月 14 日
Yes Stephen, I will do hereafter. Thanks!


その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by