Trouble using movefile to change filenames
13 views (last 30 days)
Show older comments
I have a code designed to rename a folder full of files by changing the numbers to 4 digits. for example a file text_#1.txt would be changed to text_#0001.txt. It is working perfectly unless the number is already four digits long in which case this error appears:
Error using movefile Cannot copy or move a file or directory onto itself.
Here is the script I am using:
for k = 1:numel(j)
name = j(k).name; %store the names in a variable
nums = regexp(name,'\d*','match'); %store individual name in variable
oldstr = cell2mat(nums(end)); %the old string as a number
newstr = num2str(sprintf('%04d',str2num(cell2mat(nums(end))))); %the new string as a number
old = fullfile(folder,name); %the old file
new = strrep(fullfile(folder,name),sprintf('#%s',oldstr),sprintf('#%s',newstr)); %the new filename
comp = strcmp(oldstr,newstr);
if comp == 0
movefile(old,new) %change the filenames
else
continue
end
end
it does not work when it reaches a file such as text_#1000. because this already has 4 digits the old and new filenames are identical and matlab returns the above error.
I want it to skip the file if it is already in the correct format but the same error message keeps appearing. I also tried using a try, catch loop instead of if,else. If anyone can help it would be much appreciated.
4 Comments
dpb
on 6 Aug 2014
Superficially, logic looks ok...I might rewrite the conditional as
if ~comp
movefile(old,new) %change the filenames
end
since the 'continue' is superfluous given it's placement in the loop, but that's really immaterial.
Use the debugger and step thru with one of the failing name patterns and see where the logic actual goes wrong...
Accepted Answer
Star Strider
on 6 Aug 2014
Edited: Star Strider
on 6 Aug 2014
I would use exist instead of ‘comp == 0’, something like:
if ~exist(newstr,'file')
movefile(old,new) %change the filenames
else
continue
end
No promises because I can’t test your code, but first testing to see if the file already exists would prevent the error.
2 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!