由于某种原因,下面的代码仅在批处理文件与要重命名的文件中的文件夹位于同一文件夹中,即使我指定了路径,也可以使用。当批处理文件在其他文件夹中时,我会收到一个错误,说找不到该文件。对此有任何输入吗?

@echo off&setlocal
set "name1=Bart"
set "name2=Carl"
set "name3=Judy"
for /f "delims=" %%a in ('dir C:\Users\%username%\Downloads\Export_*.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 has a good working solution for the stated problem. Another option is to simply PUSHD to where the files are located. Then you no longer need to include the path in the remainder of the code.

Other points unrelated to the question:

It is probably a good idea to initialize counter to 0, just in case some other process already set the value to a number.

You don't really need the nname variable.

I prefer to transfer the counter value to a FOR variable so that I don't need to use the CALL construct. (For those that don't know, the delayed expansion toggling is to protect ! characters that may be in the file name).

@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

Finally, FINDSTR with the /N option can eliminate the need for CALL or additional 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

那应该做你想要的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top