How to rename multiple files in a folder with variable names depending on their names in another folder?

조회 수: 10 (최근 30일)
I have several files in a directory (some examples of the names of the files are commented under the commented word (oldnames)), and I want to rename them as the commented ones ( under the commented word (newnames)). So I want to extract every number that has 4 digits (e.g., (3185)) and use it to rename the new files. I tried to extract the numbers that have 4 digits as below but it didn't work. Any suggesstions?
projectdir = 'C:\Users\Abdelrahman\Downloads\Documents\CIV312_Test';
oldfiles = dir( fullfile(projectdir, '*3*.pdf') );
oldnames = {oldfiles.name};
myindices = cellfun(@isempty,regexp(oldnames,'*3\d\d\d*','match')); % didn't work
% oldnames
% (CIV-312-3154)_Template.pdf
% 3140_CIV312.pdf
% CIV _312_3085.pdf
% CIV-312-3051.pdf
% newnames
% CIV_312_3154.pdf
% CIV_312_3140.pdf
% CIV_312_3085.pdf
% CIV_312_3051.pdf

채택된 답변

Mohammad Sami
Mohammad Sami 2020년 6월 12일
편집: Mohammad Sami 2020년 6월 12일
You dont need the *. you can do as follows.
match = regexp(oldnames,'3\d{3}','match');
  댓글 수: 5
Mohammad Sami
Mohammad Sami 2020년 6월 12일
편집: Mohammad Sami 2020년 6월 12일
regexp is for matching, to create a new string, there are various options. One of the option is to use the compose function since you are following a template name.
newnames = compose('CIV_312_%s.pdf',string(match2));
Abdel-Rahman Ashraf
Abdel-Rahman Ashraf 2020년 6월 12일
Thank you very much for your help, Mohammad. Here is my final version of what I wanted in case anyone faced such a problem in the future.
% The directory of the files
projectdir = 'C:\Users\Abdelrahman\Downloads\Documents\CIV312_Test';
% The directory of the renamed files
projectdir1 = 'C:\Users\Abdelrahman\Downloads\Documents\CIV312_Test\XX';
oldfiles = dir( fullfile(projectdir, '*.pdf') );
oldnames = {oldfiles.name};
% Replace '3\d{3}' with the first digit of the codes of the students
% For example, if the codes of students are from 5400 to 5413, replace
% '3\d{3}' with '5\d{3}'
% Notice that '3\d{3}' is found in variables 'match' and 'myindices'. So
% replace both of them.
match = regexp(oldnames,'3\d{3}','match','once');
missing = cellfun(@isempty,match);
myindices = ~cellfun(@isempty,regexp(oldnames,'3\d{3}','match'));
for i= 1 : length(match)
if myindices(i)
match1(i)= match(i);
else
match1{i} = strcat('unknown',num2str(i));
end
end
% Replace 'CIV_312_' with the code of the course
newnames= strcat('CIV_312_',match1,'.pdf') ;
for K = 1 : length(oldnames)
movefile( fullfile(projectdir, oldnames{K}), fullfile(projectdir1, newnames{K}) );
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by