Changing file name in matlab

3 views (last 30 days)
Tanmoyee Bhattacharya
Tanmoyee Bhattacharya on 4 Mar 2016
Answered: Guillaume on 4 Mar 2016
I have multiple text files. They are data_23_45.23, data_34.56_56.56, data_23_45
I want to change names and they are data_23.00_45.23, data_34.56_56.56, data_23.00_45.00
How can I change file name.

Answers (2)

Walter Roberson
Walter Roberson on 4 Mar 2016
You can rename() individual files.
I do not see any pattern in your renaming so I cannot offer code to carry out the task in general.

Guillaume
Guillaume on 4 Mar 2016
If I understood correctly:
%get list of files
folder = 'c:\somewhere\on\a\filesystem\';
files = dir(fullfile(folder, '*.txt'));
filenames = {files.name}
%find files with incomplete names
filepattern = regexp(filenames, '(data_\d+)(\.\d+)?(_\d+)(\.\d+)?(.*)', 'tokens', 'once');
isdatafile = cellfun(@numel, filepattern) == 5;
filenames(~isdatafile) = []; %eliminate files that don't conform to the basic pattern
filepattern(~isdatafile) = [];
filepattern = vertcat(filepattern{:}); %concatenate file patterns into an nx5 cell array
hasmissingpattern = cellfun(@isempty, filepattern); %find missing entries
filepattern(hasmissingpattern) = {'.00'};
%only rename files whose name has changed
filenames = filenames(any(hasmissingpattern, 2));
filepattern = num2cell(filepattern(any(hasmissingpattern, 2), :), 2);
%rename files
cellfun(@(old, new) movefile(fullfile(folder, old), fullfile(folder, strjoin(new, ''))), filenames', filepattern);

Categories

Find more on Historical Contests in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!