MATLAB: Efficient way to rename files while preserving first 5 letters and removing the rest

rename files

How can I efficiently code a MATLAB program to rename a list of files, such that first 5 letters do not change and all the letters from the letter number 6 until the end of the filename removes, without changing suffix? file names do have different lengths.

Best Answer

Hi,
get the list of files using e.g. dir:
files = dir('*.txt');
Then a simple function to use is fileparts
for i=1:length(files)
[pathname,filename,extension] = fileparts(files(i).name);
% the new name, e.g.
newFilename = filename(1:5);
% rename the file
movefile([filename extension], [newFilename extension]);
end
This assumes the script to be in the same folder as the files. Otherwise use fullfile to combine the folder and the filename into absolute file paths.
Titus