出于某种原因,即使我指定了路径,我下面的代码仅在批处理文件与要重命名的文件位于同一文件夹中时才有效。当批处理文件位于其他文件夹中时,我收到一条错误消息,指出找不到该文件。对此有什么意见吗?
@echo off&setlocal
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
for /f "delims=" %%a in ('dir C:Users%username%DownloadsExport_*.csv /b /a-d /o-d') do (
set "fname=%%~a"
set /a counter+=1
SETLOCAL ENABLEDELAYEDEXPANSION
call set "nname=%%name!counter!%%"
ren "!fname!" "!nname!%%~xa"
endlocal
)
只需添加一个工作路径:
@echo off&setlocal
set "workingpath=%userprofile%Downloads"
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
for /f "delims=" %%a in ('dir "%workingpath%Export_*.csv" /b /a-d /o-d') do (
set "fname=%%~a"
set /a counter+=1
SETLOCAL ENABLEDELAYEDEXPANSION
call set "nname=%%name!counter!%%"
ren "%workingpath%!fname!" "!nname!%%~xa"
endlocal
)
Endoro对于所述问题有一个很好的工作解决方案。另一种选择是简单地推送到文件所在的位置。然后,您不再需要在代码的其余部分包含路径。
与问题无关的其他要点:
将计数器初始化为 0 可能是个好主意,以防万一其他进程已将值设置为数字。
您实际上并不需要nname
变量。
我更喜欢将计数器值转移到 FOR 变量,这样我就不需要使用 CALL 构造。(对于那些不知道的人,延迟扩展切换是为了保护文件名中可能存在!
字符)。
@echo off
setlocal
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
pushd "C:Users%username%Downloads"
set /a counter=0
for /f "delims=" %%a in ('dir Export_*.csv /b /a-d /o-d') do (
set "fname=%%~a"
set /a counter+=1
setlocal enableDelayedExpansion
for %%N in (!counter!) do (
endlocal
ren "!fname!" "!name%%N!.csv"
)
)
popd
最后,带有/N 选项的 FINDSTR 可以消除对 CALL 或其他 FOR 的需求。
@echo off
setlocal
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
pushd "C:Users%username%Downloads"
for /f "tokens=1* delims=:" %%A in (
'dir Export_*.csv /b /a-d /o-d ^| findstr /n "^"'
) do (
set "fname=%%~B"
setlocal enableDelayedExpansion
ren "!fname!" "!name%%A!.csv"
endlocal
)
popd
@cbmanica是正确的:该目录未包含在变量fname
中,因此您必须在ren
命令中手动指定它。
@echo off
setlocal ENABLEDELAYEDEXPANSION
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
set "dir=C:Users%username%Downloads"
for /f "delims=" %%a in ('dir %dir%Export_*.csv /b /a-d /o-d') do (
set "fname=%%~a"
set /a counter+=1
:: <Comment> In the below line is the use of "call" necessary? </Comment>
call set "nname=%%name!counter!%%"
ren "!dir!!fname!" "!dir!!nname!%%~xa"
)
endlocal
这应该完全符合您的要求。