Search code examples
batch-filecmdbatch-processingbatch-rename

How to rename a file according his folder name via batch script



I have this part of batch script which is doing following:
-There is a main folder, in the main folder are two files (movie & subtitle file) and one Sub-folder called 'Subtitles'

-This script takes the name of the movie file and renames with it the subtitle file + moves the subtitle file into the 'Subtitles' sub-folder and then renames the main folder. So at the end we have one movie name, which is used on the subtitle file and on the main folder as well.

@echo off
setlocal EnableDelayedExpansion


cd /D "%~DP0"
echo BASE FOLDER: %cd%
set n=0
for /D %%a in (*) do (
set /A n+=1
cd "%%a"
echo ==================================================================
echo Processing folder: %%a


for %%b in (*.avi *.mp4 *.mkv) do set movieName=%%~Nb
echo Movie name: !movieName!
for %%b in (*.srt *.sub) do (
   move "%%b" "Subtitles\!movieName!%%~Xb"
  echo File "%%b" moved and renamed to "Subtitles\!movieName!%%~Xb"
)


cd ..
ren "%%a" "!movieName!"
echo Folder "%%a" renamed to "!movieName!" 

)
echo ==================================================================
echo %n% FOLDERS PROCESSED
pause

!!!!! What I need is following: !!!!!
-I need to make it vice versa, so the name would be taken from the main folder and not from the movie file, so the name of the main folder would be used on the movie and on the subtitle file.

Thank you!


Solution

  • @echo off
    setlocal EnableDelayedExpansion
    
    
    cd /D "%~DP0"
    echo BASE FOLDER: %cd%
    set n=0
    for /D %%a in (*) do (
    set /A n+=1
    cd "%%a"
    echo ==================================================================
    echo Processing folder: %%a
    set movieName=%%~a
    
    
    for %%b in (*.avi *.mp4 *.mkv) do (
       ren "%%~b" "!movieName!%%~Xb"
       echo Movie file "%%b" renamed to "!movieName!%%~Xb"
    )
    
    for %%b in (*.srt *.sub) do (
       move "%%~b" "Subtitles\!movieName!%%~Xb"
       echo File "%%b" moved and renamed to "Subtitles\!movieName!%%~Xb"
    )
    
    
    cd ..
    
    )
    echo ==================================================================
    echo %n% FOLDERS PROCESSED
    pause