Here is the code:
for /r %%a in (*.jpg, *.png, *.bmp, *.exe) do (
for /d %%d in (%CD%) do (
set newname=%%~nd%~x1
ren "%%~a" "!newname!%%~Xa"
echo media file in %%~fa renamed to "!newname!%%~Xa"
)
)
The main problem is that the files in the subfolders end up with filename as the parent directory name i run the bat file from.
Example of what happens:
C:\parent\name.jpg renamed to C:\parent\parent.jpg
C:\parent\child\name.jpg renamed to C:\parent\child\parent.jpg
C:\parent\child1\child2\name.jpg renamed to C:\parent\child1\child2\parent.jpg
I need:
C:\parent\1.jpg rename to C:\parent\parent.jpg
C:\parent\child\1.jpg rename to C:\parent\child\child.jpg
C:\parent\child1\child2\name.jpg renamed to C:\parent\child1\child2\child2.jpg
Any help?
This will echo the ren commands to the screen.
Remove the echo
keyword to make it actually perform the renames.
@echo off
for /r %%a in (*.jpg *.png *.bmp *.exe) do for %%b in ("%%~dpa\.") do echo ren "%%~a" "%%~nxb%%~xa"
pause
The first %%a FOR command returns each filespec recursively and the format of each file is:
c:\path\to\folder\filename.ext
The second %%b FOR is given the c:\path\to\folder
portion and \.
is added to the end making it c:\path\to\folder\.
which resolves to the current directory of to
and making it interpret folder
as the filename.
So the %%~nxb
returns the filename and extension of %%b which is folder
in this case, and that is used in the rename command. %%~xa
returns the .extension of the %%a string.
I hope that's fairly clear, along with examining the code.
The last page of the FOR /?
help describes the metavariables.