Batch File - Rename files based on parent name and (sub)folder(s) name

…衆ロ難τιáo~ 提交于 2019-12-24 07:18:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19339954/batch-file-rename-files-based-on-parent-name-and-subfolders-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!