Вопрос

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
Это было полезно?

Решение

@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.

Другие советы

I guess you could find a solution involving 2 for loop. Something like

for /f "tokens=*" %%d in ('dir /b') do ( for /f "tokens=*" %%f in ('dir /s /b %%d') do ( rename "%%f" "%%d_%%~nxf" ) )

Best Regards,

Michel.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "source=u:\Files"
pushd "%source%"
for /r %%j in (*) do (
   SET "prefix=%%~dpj"
   CALL :setpfx
   ECHO rename "%%j" "!Prefix!_%%~nxj"
)
popd
GOTO :EOF

:setpfx
SET prefix=!prefix:*%source%=!
SET prefix=%prefix:\=.%
FOR /f %%t IN ("%prefix%") DO SET prefix=%%~nt
SET prefix=%prefix:.=_%
SET "prefix=%prefix:~1%"
GOTO :eof

This may do what you require. The required commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO RENAME to REN to actually rename the files.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top