Efficient way to rename files adding prefix from higher rank folder

12 ビュー (過去 30 日間)
FD
FD 2019 年 9 月 4 日
コメント済み: bugsterkafer 2021 年 3 月 24 日
I'm trying to figure out a way to rename figure files in folders by adding a prefix which comes from a higher rank folder.
Right now, what I have is:
(many) Subject_folder > (many) SessionFolder > (one) FigureFolder > xxx.png and xxx.fig files to rename
My goal is to systematically rename .png and .fig files in order to get:
Subject_xxx.png and
Subject_xxx.fig
for each session of each different subject.
'Subject' prefix may vary in lenght, has no progressive numeration, and is always preceded by a '_'.
Thank you for any help you may provide.

回答 (2 件)

Jan
Jan 2019 年 9 月 4 日
編集済み: Jan 2019 年 9 月 4 日
% Assuming that the Subject_folder's are contained in D:\Your\Folder\ :
BasePath = 'D:\Your\Folder\';
BaseLen = length(BasePath);
FileList = dir(fullfile(BasePath, '**\*.png'));
for k = 1:numel(FileList)
Path = FileList(k).folder;
Name = FileList(k).file;
File = fullfile(Path, Name);
Subject = strtok(Path(BaseLen+1:end), '_');
newFile = fullfile(Path, [Subject, '_', Name]);
[status,msg] = movefile(File, newFile);
if status ~= 1
error(msg);
end
end
By the way, if "many" means hundreds, such that 10'000 files are concerned, use the fasterhttps://www.mathworks.com/matlabcentral/fileexchange/29569-filerename instead of movefile.

Neuropragmatist
Neuropragmatist 2019 年 9 月 4 日
You should look at fileparts:
And strsplit:
For example:
%% if these are your example filenames:
C:\file1\file2\file3\subject_folder\session_folder\figure_folder\xxx.png
C:\file1\file2\file3\subject_folder\session_folder\figure_folder\xxx.fig
%% fileparts:
>> [a,b,c] = fileparts('C:\file1\file2\file3\subject_folder\session_folder\figure_folder\xxx.png')
a =
'C:\file1\file2\file3\subject_folder\session_folder\figure_folder'
b =
'xxx'
c =
'.png'
%% followed by strsplit:
>> filenames = strsplit(a,'\')
filenames =
1×7 cell array
Columns 1 through 6
{'C:'} {'file1'} {'file2'} {'file3'} {'subject_folder'} {'session_folder'}
Column 7
{'figure_folder'}
I'm sure you can work out what to do from there...
Hope this helps,
M.

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by