Efficient way to rename files adding prefix from higher rank folder

12 views (last 30 days)
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.

Answers (2)

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

Neuropragmatist
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.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!