dir() function not working?
    2 次查看(过去 30 天)
  
       显示 更早的评论
    
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 个评论
采纳的回答
更多回答(0 个)
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

