批处理文件-根据父名称和(子)文件夹名称重命名文件 [英] Batch File - Rename files based on parent name and (sub)folder(s) name

查看:555
本文介绍了批处理文件-根据父名称和(子)文件夹名称重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

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"
  )
)

主要问题是子文件夹中的文件最终以filename为父目录名,而我是从中运行bat文件的.

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.

发生的事的示例:

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

我需要:

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

有帮助吗?

推荐答案

这将把ren命令回显到屏幕上.
删除echo关键字以使其实际上执行重命名.

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

第一个%% a FOR命令以递归方式返回每个文件规范,每个文件的格式为:
c:\path\to\folder\filename.ext

The first %%a FOR command returns each filespec recursively and the format of each file is:
c:\path\to\folder\filename.ext

第二个%% b FOR被赋予c:\path\to\folder部分,并在其末尾添加\.使其成为c:\path\to\folder\.,从而解析为当前目录to并使其将folder解释为文件名.

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.

因此,%%~nxb返回文件名和%% b的扩展名,在本例中为folder,该文件名和扩展名在重命名命令中使用. %%~xa返回%% a字符串的.extension.

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.

FOR /?帮助的最后一页描述了元变量.

The last page of the FOR /? help describes the metavariables.

这篇关于批处理文件-根据父名称和(子)文件夹名称重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆