image thumbnail
from Powerful File Name Changer by Brunno Machado de Campos
This program can easily help you change the name of a bunch of files with same characteristics.

RenameFiles.m
function varargout = RenameFiles(varargin)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%% NCA - Neuroimaging Computational Analisys %%%%%%%%%%%%%%%%%%%%
%%%%%% Brunno Machado de Campos - University of Campinas - 2012

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @RenameFiles_OpeningFcn, ...
                   'gui_OutputFcn',  @RenameFiles_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

function RenameFiles_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;

guidata(hObject, handles);

function varargout = RenameFiles_OutputFcn(hObject, eventdata, handles) 

varargout{1} = handles.output;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% START HERE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function addfiles_Callback(hObject, eventdata, handles)
global nn file path
[file,path] = uigetfile({'*.*','ALL FILES!'},'Add the Files','MultiSelect','on');
file = cellstr(file);
nn = size(file,2);

set(handles.addfilestxt,'String', sprintf('%d File(s) added!',nn))

function addprefixtxt_Callback(hObject, eventdata, handles)
if isequal(get(handles.addprefixtxt,'Value'),1)
    set(handles.addprefix,'Enable','on')
else
    set(handles.addprefix,'Enable','off')
end

function addprefix_Callback(hObject, eventdata, handles)

function espaco_Callback(hObject, eventdata, handles)

function addsufixtxt_Callback(hObject, eventdata, handles)
if isequal(get(handles.addsufixtxt,'Value'),1)
    set(handles.addsufix,'Enable','on')
else
    set(handles.addsufix,'Enable','off')
end

function addsufix_Callback(hObject, eventdata, handles)

function jumpertxt_Callback(hObject, eventdata, handles)

if isequal(get(handles.jumpertxt,'Value'),1)
    set(handles.jumper,'Enable','on')
else
    set(handles.jumper,'Enable','off')
end

function jumper_Callback(hObject, eventdata, handles)

function stoptxt_Callback(hObject, eventdata, handles)
if isequal(get(handles.stoptxt,'Value'),1)
    set(handles.stop,'Enable','on')
else
    set(handles.stop,'Enable','off')
end

function stop_Callback(hObject, eventdata, handles)

function checkinitials_Callback(hObject, eventdata, handles)
if isequal(get(handles.checkinitials,'Value'),1)
    set(handles.espacotxt,'Enable','on')
    set(handles.espaco,'Enable','on')
else
    set(handles.espacotxt,'Enable','off')
    set(handles.espaco,'Enable','off')
end

function runboton_Callback(hObject, eventdata, handles)
global nn file path
h = waitbar(0,sprintf('Please wait...%d files selected',nn));
recovery = cell(2,nn);


horas = clock;
   namefinal = sprintf('%s%d-%d-%d__%d-%d-%.f_RecoveryNames',...
       path,horas(3),horas(2),horas(1),horas(4),horas(5),horas(6));
   
fide = fopen(sprintf('%s.txt',namefinal),'w+');

Y=1;

for i = 1:nn
                waitbar(i/nn,h)
                file2Compl = fullfile(path,file{i});
                recovery{i,1} = file2Compl;
                [xd,xn,xext] = fileparts(file{i});
                

                if isequal(get(handles.addprefixtxt,'Value'),0) ||...   %verifica se est ticada a funo ou se est vazia a caixa de texto
                        isempty(get(handles.addprefix,'String'))
                    
                    if isequal(get(handles.crescenteprefix,'Value'),1) %adiciona contagem crescente se prefixo estiver desligado
                            addprefix = sprintf('%d-',i);
                    else
                            addprefix = '';
                    end 
                    
                else
                     if isequal(get(handles.crescenteprefix,'Value'),1) %adiciona contagem crescente se prefixo estiver ligado
                            addprefix = sprintf('%d-%s',i,get(handles.addprefix,'String'));
                     else
                            addprefix =  get(handles.addprefix,'String');
                     end
                end
                    
                if isequal(get(handles.addsufixtxt,'Value'),0) ||...  % adiciona sufixo
                        isempty(get(handles.addsufix,'String'))
                    
                       addsufix = '';
                else
                       addsufix = get(handles.addsufix,'String');
                end
                
                if isequal(get(handles.jumpertxt,'Value'),0) %Verifica se deseja-se pular alguns caracteres iniciais
                       jumper = 0;
                else
                       jumper = str2double(get(handles.jumper,'String')); 
                end

                if isequal(get(handles.checkinitials,'Value'),0) %Entra na opo onde se quer manter o nome (no se adiciona separadores), mas pode se adicionar sufixo e/ou prefixo jumper...stop....
                        newname = xn;

                        if isequal(get(handles.stoptxt,'Value'),0) ||... %verifica se est ticada a funo ou se a caixa de texto est vazia 
                                isempty(get(handles.stop,'String'))
                            
                            newname = xn(1+jumper:end); %se estiver vazia o nome ir at o final
                        else
                            Stopstr = strfind(xn,get(handles.stop,'String'));  %busca os indices do texto adicionado em Stop. Adiciona um ponto em que, mesmo que ainda haja separadores indica que o nome acabou.
                            
                            if isempty(Stopstr) % Caso no encontre o string de stop, o programa ir manter o nome original.
                                newname = xn(1+jumper:end);
                            else
                                newname = xn(1+jumper:Stopstr-1);%Mantem o nome, pula os caracteres desejados, e interrompe no ponto desejado (se solicitado)
                            end
                        end
                        
                        if ~isempty(get(handles.findreplace,'String')) %remove string ou substitui
                            if ~isempty(get(handles.replacetxt,'String'))   %se este no estiver vazio ento haver substituio. o string ser substituido
                            newname = regexprep(newname,get(handles.findreplace,'String'), get(handles.replacetxt,'String'));
                            else
                            newname = regexprep(newname,get(handles.findreplace,'String'), ''); %se o campo replace estiver vazio, ento o string ser somente removido.
                            end
                        end
                        
                        filenamefinal = fullfile(path,sprintf('%s%s%s%s',addprefix,newname,addsufix,xext));   % previa do nome
                        
                        if  exist(filenamefinal,'file')  % Caso haja duas pessoas com nomes resultantes iguais ele atribui  segunda o nome resultante mais indice numrico crescente.
                            newname = [newname,sprintf(' (%d)',Y)]; %atribui indice
                            Y = Y+1;
                        end
                        
                        filenamefinal = fullfile(path,sprintf('%s%s%s%s',addprefix,newname,addsufix,xext)); % redefine o nome resultante

                        movefile(file2Compl,filenamefinal,'f')
                        
                        recovery{i,2} = filenamefinal;  %salva os nomes originais e novos em uma variavel.
                        
                else %Entra na opo onde se quer usar as iniciais
                        newname = xn;
                        
                        if isempty(get(handles.espaco,'String')) %caso a pessoa tique a opo das iniciais mas no defina o separador, o programa abortar
                                warndlg('You forgot to define the name separator','Aborted!');
                                return
                        end
                        
                        if isequal(get(handles.stoptxt,'Value'),0) ||...
                                isempty(get(handles.stop,'String')) % Busca os indices do texto adicionado em Stop. Mesmo que ainda haja separadores indica que o nome acabou.
                            Espaco = strfind(xn,get(handles.espaco,'String'));
                            
                            
                        else
                            Stopstr = strfind(newname,get(handles.stop,'String'));
                                                        
                            if isempty(Stopstr)  % Caso no encontre o string de stop, o programa ir manter o nome original.
                                Stopstr = numel(newname);
                                nameInter = newname(1:Stopstr-1);
                            else
                                nameInter = newname(1:Stopstr-1); %Se encontre o STOP, ento o nome intermediario ir at um antes do indice doSTOP
                            end
                            
                            if isequal(nameInter(end),get(handles.espaco,'String')) %verifica se ao parar no string STOP, o caracter anterior  igual ao string que separa o nome. Se sim, ento ele recua mais 1 e o indice desse separador no ser incluido em Espaco.
                                nameInter = nameInter(1:end-1);
                            end
                            
                            Espaco = strfind(nameInter,get(handles.espaco,'String')); %define as posies dos separadores descontanto os que esto aps o texto de pausa (se adicionado) e exatamente antes dele.

                        end
                        
                        newname = newname([1+jumper Espaco+1]);  %O novo nome inicia no primeiro caracter aps o PULO inicial (se adicionado).
                        
                        for j = 2:size(newname,2)  %Corta as iniciais em caso de numeros ou caracteres especiais. O indice inicia em 2, para desconciderar caso a primeira inicial seja numrica ou simbolo. Isso pode ocorrer se no pular textos anteriores ao nome.
                           if double(newname(j)) < 65 || double(newname(j)) > 90
                               if double(newname(j)) < 97 || double(newname(j)) < 122
                                  newname = newname(1:j-1);
                                  break
                              end
                           end
                        end
                        
                        aVer = sprintf('%s%s%s%s%s',path,addprefix,newname,addsufix,xext); %simula o nome final
                        
                        if  exist(aVer,'file')  % Caso haja duas pessoas com iniciais iguais ele atribui  segunda o nome completo + as iniciais.
                            newname2 = xn(1+jumper:Espaco(1)-1); %seleciona o primeiro nome
                            newname = sprintf('%s_%s',newname2,newname(2:size(newname,2))); %atribui o primeiro nome
                        end
                        
                        
                        if ~isempty(get(handles.findreplace,'String'))
                            if ~isempty(get(handles.replacetxt,'String'))
                            newname = regexprep(newname,get(handles.findreplace,'String'), get(handles.replacetxt,'String'));
                            else
                            newname = regexprep(newname,get(handles.findreplace,'String'), '');
                            end
                        end
                        
                        filenamefinal = fullfile(path,sprintf('%s%s%s%s',addprefix,newname,addsufix,xext));   
                        movefile(file2Compl,filenamefinal,'f')
                        
                        recovery{i,2} = filenamefinal;

                end
                fprintf(fide,'%d - %s%s \r\n    %s\r\n\r\n',i,path,xn,filenamefinal);   % salva as alteraoes em um txt.
end

   close(h)
  
   save(sprintf('%s.mat',namefinal),'recovery') %salava as alteraoes em um .mat que poder ser usado para restaurar os nomes antigos
   fclose(fide);

function findreplace_Callback(hObject, eventdata, handles)


function recoveryopen_Callback(hObject, eventdata, handles)
wtf = warndlg('The files must to be in the same folder that the program saved them!','Attention!');

waitfor(wtf);

[file2,path2] = uigetfile({'*.mat','Matlab File'},'Add the "RecoveryNames" file created by the program','MultiSelect','off');

load(fullfile(path2,file2));

nn2 = size(recovery,1);

h = waitbar(0,sprintf('Please wait...%d files selected',nn2));

for i = 1:nn2
   
   if isempty(recovery{i,1})
       break
   end
   
   waitbar(i/nn2,h)
   
   movefile(recovery{i,2},recovery{i,1},'f');
end

function crescenteprefix_Callback(hObject, eventdata, handles)

function replacetxt_Callback(hObject, eventdata, handles)

Contact us