MATLAB Answers

Renaming Excel Files Using MATLAB Code

17 views (last 30 days)
Faroq Al-Rjoub
Faroq Al-Rjoub on 21 Mar 2020
Edited: Subhamoy Saha on 21 Mar 2020
Hi Matlab
I have a lot of Excel files that i am trying to rename by deleting the first almost 80 characters in the names. The length of the names differ from on file to another. I am trying to keep the last 7 characters in the name. Here is an example of the current name of the file, Submit LEGO Kit Inventory Sheet Here_PulpFiction_attempt_2018-03-19-00-00-22_LegoPartInventory_TEAM852 an I try to rename it to TEAM852. Remember that the length of the names differ. I need a code that would allow me to choose the folder that contains all files that need the name changed, then change the name of the all files by deleting all the characters except the last 7 characters. Please Help.
Thank you

  0 Comments

Sign in to comment.

Answers (1)

Subhamoy Saha
Subhamoy Saha on 21 Mar 2020
Edited: Subhamoy Saha on 21 Mar 2020
Change the file extension according to your need.
datafolder=uigetdir();
% files=dir(datafolder); % if you don't have any subfolder or other type of files then you can use this line
files=dir([datafolder '\*.xlsx']); % if you have subfolders or different type of files
for kk=1:length(files)
oldname=fullfile(datafolder,files(kk).name);
[~,fname,ext]=fileparts(files(kk).name);
fname=fname(end-8:end); % taking only last 7 characters excluding extension
newname = fullfile(datafolder,[fname,ext]);
movefile(oldname, newname);
end
Or you can use the following code. You have to select any one file in your desired folder. The following code will rename all those files having with similar file extension. It is also applicable where the selected folder conatins mixed type of files or subfolders.
[file,datafolder]=uigetfile('*.*');
[~,~,ext]=fileparts(file);
files=dir([datafolder, '*', ext]);
for kk=1:length(files)
oldname=fullfile(datafolder,files(kk).name);
[~,fname,ext]=fileparts(files(kk).name);
fname=fname(end-8:end); % taking only last 7 characters excluding extension
newname = fullfile(datafolder,[fname,ext]);
movefile(oldname, newname);
end

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!