- 1 year ago
Batch file to copy and rename files from multiple subdirectories recursively
Comment
1 / 1
You can use a batch file to copy and rename files from multiple subdirectories recursively by combining the FOR /R
loop with the XCOPY
command. Here's an example:
batch@echo off
set "source=C:\SourceFolder"
set "destination=C:\DestinationFolder"
for /R "%source%" %%F in (*) do (
set "filepath=%%~dpF"
set "filename=%%~nxF"
setlocal enabledelayedexpansion
set "newname=!filename:substring=replace!"
xcopy "%%F" "%destination%\!newname!" /Y
endlocal
)
In the above example:
- Set the
source
variable to the root directory containing the files you want to copy and rename. - Set the
destination
variable to the directory where you want to copy the files. - The
FOR /R
loop recursively iterates through each file in the source directory and its subdirectories. - Within the loop, the
filepath
variable is set to the directory path of the current file, and thefilename
variable is set to the name of the current file. - The
setlocal enabledelayedexpansion
command enables the delayed expansion of variables. - The
set "newname=!filename:substring=replace!"
line replaces the desired substring in thefilename
variable with the desired replacement. - The
XCOPY
command is used to copy the file from the source to the destination, specifying the new name with!newname!
. - The
/Y
option in theXCOPY
command overwrites any existing files with the same name in the destination folder. - The
endlocal
command ends the local variable scope.
Modify the substring
and replace
values in the set "newname=!filename:substring=replace!"
line according to your renaming requirements.
Save the batch file with a .bat
extension and run it. It will recursively copy and rename the files from the source directory and its subdirectories to the destination directory.