Efficient way to rename files adding prefix from higher rank folder

12 vues (au cours des 30 derniers jours)
FD
FD le 4 Sep 2019
Commenté : bugsterkafer le 24 Mar 2021
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.

Réponses (2)

Jan
Jan le 4 Sep 2019
Modifié(e) : Jan le 4 Sep 2019
% 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 le 4 Sep 2019
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.

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Produits


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by