dir() function not working?
    2 views (last 30 days)
  
       Show older comments
    
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
0 Comments
Accepted Answer
More Answers (0)
See Also
Categories
				Find more on Startup and Shutdown in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!