Efficient way to rename files adding prefix from higher rank folder

12 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by