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

12 ビュー (過去 30 日間)
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!

採用された回答

Murugan C
Murugan C 2020 年 2 月 13 日
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 件のコメント
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 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by