我正在创建一个批处理文件,在其中需要列出指定文件夹中所有文本文件的名称,然后将其存储并从数组中检索。在批处理文件中是否有可能实现此功能?我的当前代码如下,用于列出测试文件:
dir *.txt /b
任何帮助都非常感激。
我正在创建一个批处理文件,在其中需要列出指定文件夹中所有文本文件的名称,然后将其存储并从数组中检索。在批处理文件中是否有可能实现此功能?我的当前代码如下,用于列出测试文件:
dir *.txt /b
模拟数组
批处理文件中只有字符串这一种变量类型。但是,可以通过使用几个名称相同但末尾带有数字ID的变量来模拟数组,例如:
Array[1] Array[2] Array[3] Array[4] etc...
获取命令输出
第一步是将命令输出放入一个变量中。我们可以使用 for /f
循环。
for /f %%G in ('dir *.txt /b') do set filename=%%~G
('')
子句和/f
选项指定收集命令输出。请注意,由于变量覆盖,您得到的文件名始终是最后一个显示的文件名。可以通过追加来解决此问题,但这超出了本答案的范围。
[n]
的数组名称filename
,其中n
是数字ID。setlocal enableDelayedExpansion
set /a ID=1
for /f "delims=" %%G in ('dir *.txt /b') do (
set filename[!ID!]=%%~G
set /a ID+=1
)
set filename
endlocal
需要注意两点:
我在循环中添加了"delims="
以确保它与默认分隔符正常工作。
我用!ID!
替换了%ID%
,因为涉及到延迟扩展。简而言之,当禁用延迟扩展时,在运行时之前整个for循环都已经被解析,具有新值的变量不会更新块(()
)结构;如果启用,则这些变量会更新。!ID!
表示每次循环都需要更新。
@echo off
Title Populate Array with filenames and show them
set "MasterFolder=%userprofile%\desktop"
Set LogFile=%~dpn0.txt
If exist "%LogFile%" Del "%LogFile%"
REM Iterates throw all text files on %MasterFolder% and its subfolders.
REM And Populate the array with existent files in this folder and its subfolders
echo Please wait a while ... We populate the array with filesNames ...
SetLocal EnableDelayedexpansion
@FOR /f "delims=" %%f IN ('dir /b /s "%MasterFolder%\*.txt"') DO (
set /a "idx+=1"
set "FileName[!idx!]=%%~nxf"
set "FilePath[!idx!]=%%~dpFf"
)
rem Display array elements
for /L %%i in (1,1,%idx%) do (
echo [%%i] "!FileName[%%i]!"
(
echo( [%%i] "!FileName[%%i]!"
echo Path : "!FilePath[%%i]!"
echo ************************************
)>> "%LogFile%"
)
ECHO(
ECHO Total text files(s) : !idx!
TimeOut /T 10 /nobreak>nul
Start "" "%LogFile%"
>con
。即使没有>con
,脚本也能正常工作。 - user6250760