Search code examples
windowsbatch-fileprefix

Adding Parent Directory name as Prefix to sub directory files using batch file


Adding Parent Directory name as Prefix to sub directory files using batch file

I need to add the prefix of the parent directory to all the files present in sub directories

for example we receive html and text files within Directories 101 as parent directory and Creatives as sub directory

F:\Files\101\Creatives\filename.htm and filename.txt
F:\Files\102\Creatives\filename.htm and filename.txt
F:\Files\103\Creatives\filename.htm and filename.txt

here I want to omit the sub directory name (Creatives) and add 101_, 102_, 103_ as the prefix to the filenames present in sub directories

example 101_filename.htm also for the text file as 101_filename.txt in sub folders

with the below code I can add the prefix to the sub folder files but I can only replace it with a static value (Prefix_), here I need to add the first directory name(101, 102, etc) as prefix to all the files present in (F:\Files) folder

@echo off
pushd "F:\Files"
for /r %%j in (*) do (
   rename "%%j" "Prefix_%%~nxj"
)
popd

Solution

  • @echo off
    pushd "F:\Files"
    for /d %%P in (*) do for /f "delims=" %%F in ('dir /b /s /a-d "%%P"') do rename "%%F" "%%P_%%~nxF"
    popd
    

    The inner loop is FOR /F with DIR command instead of FOR /R to eliminate possibility of loop renaming the same file twice.