Matlab: how to rename bulk files if varying length

107 views Asked by At

I am trying to rename over a thousand files of varying length. For example, my original file names are:

1-1.txt
1-13.txt
12-256.txt
...

I would like these files to appear as follows:

100000-1-1.txt
100000-1-13.txt
100000-12-256.txt
...

I have been trying to use the following script:

d = 'directoryname';

names = dir(d);
names = {names(~[names.isdir]).name};

len  = cellfun('length',names);
mLen = max(len);

idx   = len < mLen;
len   = len(idx);
names = names(idx);

for n = 1:numel(names)
    oldname = [d names{n}];
    newname = sprintf('%s%100000-*s',d,mLen, names{n});
    dos(['rename','oldname', 'newname']); % (1)
end

What am I doing wrong? Thanks in advance for your help!!

2

There are 2 answers

12
Divakar On BEST ANSWER

See if this works for you -

add_string = '100000-'; %//'# string to be concatenated to all filenames
pattern = fullfile(d,'*.txt') %// we are renaming only .txt files

files_info = dir(pattern)
org_paths = fullfile(d,{files_info.name})
new_paths = fullfile(d,strcat(add_string,{files_info.name}))

if ~isempty(org_paths{1}) %// Make sure we are processing something
    cellfun(@(x1,x2) movefile(x1,x2), org_paths, new_paths); %// rename files
end

Edit

add_string = '100000-'; %//'# string to be concatenated to all files
pattern = fullfile(d,'*.txt') %// Rename .txt files

files_info = dir(pattern);

f1 = {files_info.name};
org_paths = cellfun(@(S) fullfile(d,S), f1, 'Uniform', 0);

f2 = strcat(add_string,f1);
new_paths = cellfun(@(S) fullfile(d,S), f2, 'Uniform', 0);

if numel(org_paths)>0
    if ~isempty(org_paths{1}) %// Make sure we are processing something
        cellfun(@(x1,x2) movefile(x1,x2), org_paths, new_paths); %// rename all files
    end
end
1
Luis Mendo On

I don't really get what you are doing with len and mLen, but assuming that's correct, you just need the following changes within the for loop:

for n = 1:numel(names)
    oldname = [d filesep names{n}]; %// include filesep to build full filename
    newname = sprintf('100000-%s', names{n}); %// prepend '100000-' to names{n}
    %// or replace by the simpler: newname = ['100000-' names{n}];
    dos(['rename' oldname ' ' newname]); % (1) %// oldname and newname are variables
end