Search code examples
windowsbatch-filerenamerenaming

Windows Batch: Rename a folder to the name of a file inside


I have ~3000 folders, each with multiple files in it. Each folder contains a txt file, with a few other file types. The folder names are hashed, so right now it's a jumble of random digits. I want to rename each folder to the same name as the txt file that is inside that folder. For example:

123456/myfile.txt

Should become:

myfile/myfile.txt

The folders do not contain any subfolders, if that matters. Any help is greatly appreciated!


Solution

  • for /d %%a in (*) do (
      for %%b in ("%%a\*.txt") do (
        ECHO ren "%%a" "%%~nb"
      )
    )
    

    use a for /d to iterate over your folders and another plain for to get the filename (assuming, there is exactly one .txt file in each folder). %%~nb gets the name only without extension).

    NOTE: after troubleshooting, remove the ECHO to enable the rename command.