Windows批处理文件:从路径获取最后的文件夹名称 [英] Windows batch file: get last folder name from path

查看:822
本文介绍了Windows批处理文件:从路径获取最后的文件夹名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重命名e.\ study \ pubpmc \ test \ extracted的许多子目录之一中的.jpg文件.

I'm trying to rename .jpg files which is in one of many subdirectories of e:\study\pubpmc\test\extracted.

我想将文件重命名为LastFolderName_ImageName.jpg. (例如,如果Figure1.jpg位于e:\ study \ pubpmc \ test \ extracted \ folder1中 我希望将其重命名为:folder1_Figure1.jpg)

I want to rename files to LastFolderName_ImageName.jpg. (For example if Figure1.jpg is in e:\study\pubpmc\test\extracted\folder1 I want it to be renamed like this: folder1_Figure1.jpg)

所以我需要从文件路径中取出最后一个文件夹名称. 由于这是我第一次使用批处理脚本,因此我很难过.

So I need to take out the last folder name from the file's path. Since it's my first time with batch scripting, I'm having a hard time.

我用谷歌搜索并制作了类似的代码 但似乎无法解决问题.

I googled and made code similar to it but it doesn't seem to work out.

您能帮我一下,告诉我我做错了什么吗? 谢谢! :)

Can you help me with it and tell me where I've done wrong? Thank you! :)

@echo off
cd /D "e:\study\pubpmc\test\extracted"
for /r %%f in (*.jpg) do (
set mydir=%%~dpf
set mydir=%mydir:\=;%

for /f "tokens=* delims=;" %%i in (%mydir%) do call :LAST_FOLDER %%i
goto :EOF

:LAST_FOLDER
if "%1"=="" (
    @echo %LAST%
    goto :EOF
    )

set LAST=%1
SHIFT

goto :LAST_FOLDER


)

推荐答案

JosefZ解释了您的代码中的明显问题,但他未能指出一个细微的问题,尽管他的代码已将其修复:

JosefZ explains the obvious problems with your code, but he failed to point out a subtle problem, though his code fixed it:

FOR/R(以及简单的FOR)在完成扫描磁盘驱动器之前立即开始迭代.循环可能会重复已经命名的文件!这将导致它被重命名两次,从而产生错误的结果.解决方案是将FOR/F与命令'DIR/B'一起使用,因为FOR/F始终在 迭代之前处理该命令以使其完成.

FOR /R (as well as the simple FOR) begin iterating immediately, before it has finished scanning the disk drive. It is possible for the loop to reiterate the already named file! This would cause it to be renamed twice, giving the wrong result. The solution is to use FOR /F with command 'DIR /B', because FOR /F always processes the command to completion before iterating.

JosefZ还提供适用于大多数情况的代码.但是,有一个更简单的解决方案始终可以起作用:

JosefZ also provides code that works for most situations. But there is a much simpler solution that works always:

@echo off
for /f "delims=" %%A in (
  'dir /b /s /a-d "e:\study\pubpmc\test\extracted\*.jpg"'
) do for %%B in ("%%A\..") do ren "%%A" "%%~nxB_%%~nxA"

"%%A\.."将文件名视为文件夹,然后转到父文件夹.因此%%~nxB给出了父文件夹的名称.

The "%%A\.." treats the file name as a folder and walks up to the parent folder. So %%~nxB gives the name of the parent folder.

该命令可以直接从命令行(无批处理)作为一个长衬板运行:

The command could be run as a long one liner, directly from the command line (no batch):

for /f "delims=" %A in ('dir /b /s /a-d "e:\study\pubpmc\test\extracted\*.jpg"') do @for %B in ("%A\..") do @ren "%A" "%~nxB_%~nxA"

这篇关于Windows批处理文件:从路径获取最后的文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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