how to properly rename files like pic0001 while keeping their order

I am working with thousands of bmp images and try to rename them properly to run my code. But I need to pad the zeros in front and make them such as frame0001, frame0002 and ... However when I use this codes although I get the proper names but they do not follow the right trend and it starts and ends from soemwhere arbitrary not the 1st frame. The actual images are in proper order starting with frame1, frame2, ....
this is the code I am currently using.
dirData = dir('*.bmp'); %# Get the selected file data
fileNames = {dirData.name}; %# Create a cell array of file names
for iFile = 1:numel(fileNames) %# Loop over the file names
newName = sprintf('image%04d.bmp',iFile); %# Make the new name
movefile(fileNames{iFile},newName); %# Rename the file
end

Answers (2)

If I understand it correctly you might have the following situtation:
% example filenames where
filenames = {'file1.bmp',
'file10.bmp',
'file11.bmp',
'file2.bmp',
'file3.bmp',
'file4.bmp',
'file5.bmp',
'file6.bmp',
'file7.bmp',
'file8.bmp',
'file9.bmp' };
newfilenames = regexprep(filenames,'(\d+)','${sprintf(''%04s'',$1)}')
newfilenames =
'file0001.bmp'
'file0010.bmp'
'file0011.bmp'
'file0002.bmp'
'file0003.bmp'
'file0004.bmp'
'file0005.bmp'
'file0006.bmp'
'file0007.bmp'
'file0008.bmp'
'file0009.bmp'
for ii = 1:numel(filenamse)
movefile(newfilenames{ii},filenames{ii});
end
I do not see anything wrong with the above code and it works just fine for me. Are you sure you are not just not seeing the new files?

Asked:

on 1 Aug 2012

Commented:

on 8 Sep 2023

Community Treasure Hunt

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

Start Hunting!