Files getting moved to another folder while renaming using regexp and movefile command
Show older comments
This is with reference changing file name using matlab code
(1) I have bunch of pdf files with tiles “AuthorA_2005_ First Paper”, “AuthorB_1955_ Second Paper”, “AuthorC_2018_ Third Paper” and so on. I would like to change the name to such a way that there is no space between year and title of paper, i.e. “AuthorA_2005_First Paper”, “AuthorB_1955_Second Paper”, “AuthorC_2018_Third Paper”. For this, I have written the following code:
clear; clc;
folder_name = 'C:\Users\SREERAJ\Desktop\1stone';
dir_infrmatn = dir( fullfile(folder_name, '*.pdf') );
prvs_name = {dir_infrmatn.name};
fun1 = @(x) regexprep(x, '^(.+\d{4})_ (.+)$', '$1_$2');
newfilenames1 = cellfun(fun1, prvs_name, 'UniformOutput', false);
for k = 1 : length(prvs_name)
movefile( fullfile(folder_name, prvs_name{k}), fullfile(folder_name, newfilenames1{k}) );
end
When I run this command, the names of file names are changed as I wanted in the prescribed folder only.
(2) There are another set of files which has the format “2019-06-20 First paper by Author A”, “2019-07-18 Second paper by Author B”, “2019-08-01 3rd Paper by AuthorC”, “19800925FourthPaper_Author D”, “19900329Fifth paper(NiceOne) of great interest”, “20181011Sixth paper_Author E”. I want to convert it into format like “20190620First paper by Author A”, i.e. “yearmonthdayName.pdf” (name can have spaces between them). The code that I have written for them is
clear; clc;
folder_name = 'C:\Users\SREERAJ\Desktop\2ndone';
dir_infrmatn = dir( fullfile(folder_name, '*.pdf') );
prvs_name = {dir_infrmatn.name};
fun2 = @(x) regexprep(x, '^(\d{4})-(\d{2})-(\d{2}) (.+)$', '$1$2$3$4');
newfilenames2 = cellfun(fun2, prvs_name, 'UniformOutput', false);
for k = 1 : length(prvs_name)
movefile( fullfile(folder_name, prvs_name{k}), fullfile(folder_name, newfilenames2{k}) );
end
When I run this code, I am getting an error message “Error using movefile Cannot copy or move a file or directory onto itself.”
Now, if I inserted a command folder_name5=' C:\Users\SREERAJ\Desktop\Done'; before “dir_infrmatn” and modified the command inside the for loop to “movefile( fullfile(folder_name, prvs_name{k}), fullfile(folder_name5, newfilenames2{k}) );”, the program runs fine, but the contents are moved (not copied) from folder_name to folder_name5 and renamed there.
My question is why is this (moving the file and renaming) happening for the second case, not for the first one, even though both of the code have similar structure
Thanks in advance.
P.S. (i). The codes that I have used is from Stackoverflow
(ii). I am not uploading the files, Anybody can try to name a pdf file in this fashion and try it.
Accepted Answer
More Answers (0)
Categories
Find more on File Operations 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!