使用批处理脚本将文件名与文件号组合

Combining file names with file numbers using a batch script

我正在尝试为特定文件夹中的文件编号。我的目标是输出文件的字母位置和名称。因此,对于其中包含例如两个文件的文件夹(hello.txtworld.txt),我希望脚本输出像这样:

File 1 is hello  
File 2 is world  

这是我的脚本:

@echo off
cls

setlocal enabledelayedexpansion
set folder=c:\test
set count=0

for /r "%folder%" %%a in (*.*) do (
    set file_!count!=%%~na
    set /a count+=1
    call :SUB
    )

if !count!==0 goto :EOF 

goto :EOF

:SUB
echo File !count! is file_%count%

这是输出:

File 1 is file_1
File 2 is file_2

如您所见,文件名的输出与我的预期不符。

我尝试了文件名变量的不同变体:

变体 2:

%file_!count!%

输出 2:

File 1 is world
File 2 is world

变体 3:

%file_count%

输出 3:

File 1 is
File 2 is

你发现我的错误了吗?

将变量名作为参数传递给被调用的例程

 ...
 call :SUB !count! file_!count!
 ....


:SUB
echo echo File %1 is !%2!

:SUB 代码必须是这个:

:SUB
echo File !count! is !file_%count%! 

这是做同样事情的不同方法:

@echo off
cls

setlocal enabledelayedexpansion
set folder=c:\test

for /F "tokens=1* delims=:" %%a in ('dir /B /A-D /S "%folder%" ^| findstr /N "^"') do (
   set file_%%a=%%~nb
   echo File %%a is %%b
)