简体   繁体   中英

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

Here I made this my self. I created a similar situation to yours and it worked fine for me. However you have to specify the location to copy all the files to.

for /d %%a in (*) do (
cd %%a
for /r %%b in (*) do (
copy %%b C:\ [root] \%%a%%~xb
)
cd..
)
pause

Hopes this helps.

Yours Mona.

This uses Mona's code but handles long filenames. Test it on some sample folders.

Call it renfolder.bat or something as rename.bat uses the name of an internal command.

@echo off
for /d %%a in (*) do (
cd "%%a"
for %%b in (*) do (
echo copying "%%a%%~xb"
copy "%%b" "\%%a%%~xb" >nul
)
cd..
rd "%%a"
)
pause

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"
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM