Search code examples
windowsbatch-filefile-renamebatch-rename

Windows batch script to name files after containing subfolder and copy to root


consider following folder structure:

root
  Folder1
    file1.txt
    file2.dat
  Folder2
    file3.doc
    file4.pdf
  rename.bat

I want to rename the files (using rename.bat) according to the name of the respective subdirectories, copy them to the root directory and delete the subfolders so that I get

root
  Folder1.txt
  Folder1.dat
  Folder2.doc
  Folder2.pdf
  rename.bat

Actually I know this is possible (and actually with very few lines of code) since I already found the code somewhere some time ago. Sadly I lost my scipt and am not able to find the code again now.

Regards, Eduard


Solution

  • Thanks for the answers!

    I improved upon your code to work as intended so it perfectly fit my needs now:

    @echo off
    for /d %%a in (*) do (
      cd "%%a"
      for %%b in (*) do (
        echo moving "%%a\%%b" to "%%a%%~xb"
        move "%%b" "..\%%a%%~xb"
      )
      cd ..
      rd "%%a"
    )