How to iteratively increase number in filename?

I have a list of files named ######-######-####XX, where # is an arbitrary number (same for all files), and XX is 01:20. I'm trying to rename all the files by adding 1 to the frame number, so the files will effectively go from 02:21. I tried using the code below, but soon realized that adding 1 to 9 will not make 19 go to 20. Does anyone have a better solution for this? Thanks in advance.
list=dir('*.dcm')
names={list.name}
for m=1:length(list)
revnames=names(end:-1:1)
[~,name,ext]=fileparts(revnames{m})
OldName=[name,ext]
A=num2str(name)
A(end)=(A(end)+1)
NewName=[A,ext]
copyfile(OldName,NewName)
clear A
end

 Accepted Answer

dpb
dpb on 10 Feb 2015
Edited: dpb on 10 Feb 2015
list=dir('*.dcm');
for m=length(list):-1:1
[~,name,ext]=fileparts(list.name{m});
basename=name(1:end-1); % strip the last two (numeric) characters
basenumb=str2num(name(end-1):end); % convert the numeric characters
newnum=basenumb+1; % and increment it
copyfile(list(m).name,fullfile([basename num2str(newnum,'%02d')],ext));
end
NB:
Must run the loop from top down to avoid overwriting the existing '02' file with the renamed '01', one. Also, this presumes the dir() list is returned sorted which is generally so although "defensive programming" would be to do so to ensure it is before beginning the loop.
Also, if you don't know a priori are only two numeric digits at the end would need to do a search to determine that length. If the last '#' character were also to be numeric that could be problematic to discern w/o some other decoding rules.

3 Comments

Thanks for the help! I did tweak it slightly (removed the fullfile function, and some parentheses were slightly off), but it works perfectly.
Don't remove the fullfile: this is the recommended way of generating paths strings from directories and filenames.
Noticed did miss closing paren on the str2num call; corrected. Any others I didn't see?
I agree with Stephen's comment on fullfile; while you can do without it, it does make for simpler and particularly more robust coding in general in not having to worry about the existence/non-existence of separating slashes, etc. It would be nice if it were also a little more flexible but it is what it is...

Sign in to comment.

More Answers (0)

Categories

Asked:

on 9 Feb 2015

Edited:

dpb
on 10 Feb 2015

Community Treasure Hunt

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

Start Hunting!