Warren
Warren

Reputation: 803

How rename batch subdirectories in delphi?

I have hundreds of subdirectories in a folder and there are hundreds of subfolders in subdirectories. I want to check if the subfolder name include '(number)', if the subfolder contains it, I want to prefix '(number)' as the subfolder name: For example:

rootfolder
       --- subfolder1
                 ---subfolder11(100082)
                        --- file1.txt
        --- subfolder2(100083)
                  ---subfolder22(100085)
                         --- file2.txt 
                         --- subfolder222
                                     ---subfolder2222(80001)
                                                        ---file3.txt

I want to have:

rootfolder
       --- subfolder1
                 ---(100082)subfolder11
                        --- file1.txt
        --- (100083)subfolder2
                  ---(100085)subfolder22
                         --- file2.txt 
                         --- subfolder222
                                    --- (80001)subfolder2222
                                                        --- file3.txt

Can you help me? Thanks a lot in advance.

Upvotes: 0

Views: 1207

Answers (3)

kludg
kludg

Reputation: 27493

Here is a code that renames subdirectories, customize it for your needs:

procedure ProcessDir(const DirName: string);
var
  Path, NextDir: string;
  F: TSearchRec;

begin
  Path:= DirName + '/*.*';
  if FindFirst(Path, faAnyFile, F) = 0 then begin
    try
      repeat
        if (F.Attr and faDirectory <> 0) then begin
          if (F.Name <> '.') and (F.Name <> '..') then begin
            NextDir:= DirName + '/' + F.Name;
            ProcessDir(NextDir);
// generate new folder name here, next line just for testing
            RenameFile(NextDir, NextDir + '_Renamed');
          end;
        end;
      until FindNext(F) <> 0;
    finally
      FindClose(F);
    end;
  end;
end;

Upvotes: 2

Martin James
Martin James

Reputation: 24907

Well, as an example, this is my extract that does nasty things to folder trees - it does not rename them, it destroys them:

procedure splatDirectory(const dirSpec:string);
var searchRec:TsearchRec;
    searchResult:integer;
begin
  searchResult:=findFirst(dirSpec+'\*.*',faDirectory,searchRec);
  try
    while (0=searchResult) do
    begin
      if ((searchRec.attr and faDirectory)>0) then
      begin
        if (searchRec.name<>'.') and (searchRec.name<>'..') then
          splatDirectory(dirSpec+'\'+searchRec.Name)
      end
      else
        deleteFile(dirSpec+'\'+searchRec.Name);
      searchResult:=findNext(searchRec);
    end;
  finally
    findClose(searchRec);
  end;
  removeDir(dirSpec);
end;

This does work - copied from working code.

Upvotes: 3

Chris Thornton
Chris Thornton

Reputation: 15817

You need a recursive directory search to find all of the folders. And rename them, from the bottom-up.

Upvotes: 1

Related Questions