MATLAB Answers

FD
0

Efficient way to rename files adding prefix from higher rank folder

Asked by FD
on 4 Sep 2019
Latest activity Edited by Jan
on 4 Sep 2019
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.

  0 Comments

Sign in to comment.

Products


Release

R2017a

2 Answers

Answer by Neuropragmatist on 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.

  0 Comments

Sign in to comment.


Answer by Jan
on 4 Sep 2019
Edited by Jan
on 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.

  0 Comments

Sign in to comment.