Hi,
I am new to Batch script.
What I am trying to do is rename files.
For example, a file’s full path is
C:\testb\first.txt
I want to change this file name “first.txt” to “C_testb_first.txt” OR “testb_first.txt”
And do this rename for all files in this folder “testb” and all files in subdirectory also.
Can anyone help me please?
Regards
Ruu
Batch file to Rename files to their file path
Moderator: DosItHelp
Re: Batch file to Rename files to their file path
Remove the echo if the ren command does what you want.
Code: Select all
@echo off
for /f "delims=" %%a in ('dir /a-d /b /s') do call :next "%%a"
pause
goto :EOF
:next
set "name=%~1"
set "name=%name::=%"
set "name=%name:\=_%"
echo ren "%~1" "%name%
Re: Batch file to Rename files to their file path
Ruu wrote:OR “testb_first.txt”
Code: Select all
@echo off
setlocal enableextensions
for /f "delims=" %%a in ('dir /a-d /b /s') do call :next "%%a"
pause
goto :EOF
:next
set "name=%~1"
set "name=%name:\=_%"
echo ren "%~1" "%name:~3%
goto :EOF
Re: Batch file to Rename files to their file path
please note:
- the call:function "%file name%" code doesn't work with files with % in the name
- if delayed expansion is enabled the code also doesn't work with files with ! or ^ in the name
Re: Batch file to Rename files to their file path
Love this! Saved us A lot of grief over renaming a couple of hundred files. Thank you!foxidrive wrote:Remove the echo if the ren command does what you want.Code: Select all
@echo off
for /f "delims=" %%a in ('dir /a-d /b /s') do call :next "%%a"
pause
goto :EOF
:next
set "name=%~1"
set "name=%name::=%"
set "name=%name:\=_%"
echo ren "%~1" "%name%
We modified this batch by changing ren to move since ren left the file in the same directory and we wanted to flatten the directory structure since the resulting filenames included the directory structure in the filenames.
Re: Batch file to Rename files to their file path
xxcopy does a good job of flattening folder structures.
Re: Batch file to Rename files to their file path
That it does, but since we needed to rename the file with the path included, this batch worked great.Squashman wrote:xxcopy does a good job of flattening folder structures.