dir() function not working?

5 views (last 30 days)
John
John on 19 Mar 2012
Hello,
I'm trying to rename some files using the code below. It works if I list the file names at the beginning but there are many files in the folder so I wanted to use the dir()function but it won't work for some reason. Would anybody know why?
Thanks
Working code:
files = {'RW.a_process',...
'Copy of RW.a_process',...
'Copy (2) of RW.a_process',...
'Copy (1000) of RW.a_process'}
for k = 1 : length(files)
oldFileName = files{k}
leftParenthesisLocation = strfind(oldFileName, 'Copy (');
if leftParenthesisLocation >= 1
% Handle cases of Copy (nnn) of RW.a_process
rightParenthesisLocation = strfind(oldFileName(leftParenthesisLocation:end), ')');
if rightParenthesisLocation > 1
strNumber = oldFileName(leftParenthesisLocation+6:rightParenthesisLocation-1)
% Get name to the right of the right parenthesis.
newFileName = oldFileName(rightParenthesisLocation+5:end);
[folder, baseFileName, ext] = fileparts(newFileName);
newFileName = sprintf('%s%s%s', baseFileName, strNumber, ext);
fprintf('New Filename = %s\n', newFileName); % Print blank line.
end
Not working code:
files = dir('*.a_process');
for k = 1 : length(files)
oldFileName = files{k}
leftParenthesisLocation = strfind(oldFileName, 'Copy (');
if leftParenthesisLocation >= 1
% Handle cases of Copy (nnn) of RW.a_cycle
rightParenthesisLocation = strfind(oldFileName(leftParenthesisLocation:end), ')');
if rightParenthesisLocation > 1
strNumber = oldFileName(leftParenthesisLocation+6:rightParenthesisLocation-1)
% Get name to the right of the right parenthesis.
newFileName = oldFileName(rightParenthesisLocation+5:end);
[folder, baseFileName, ext] = fileparts(newFileName);
newFileName = sprintf('%s%s%s', baseFileName, strNumber, ext);
fprintf('New Filename = %s\n', newFileName); % Print blank line.
movefile(oldFileName, newFileName)
end

Accepted Answer

Honglei Chen
Honglei Chen on 19 Mar 2012
You need to use
oldFileName = files(k).name
see

More Answers (0)

Categories

Find more on Display Image in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!