首页 > 解决方案 > 将每个文件名批量设置为不同的变量

问题描述

目录中有随机数量的具有相同扩展名的文件。

例如

file1.txt
file2.txt
file3.txt

需要扫描目录并将每个文件名设置为一个新变量。我们可以这样做:

        for %%A in ("*.txt") do (
            set var=%%~nA
        )

但是它将文件名设置为同一个变量,最后只有最后一个变量是活动的,所以在这个例子中它总是只是file3.

需要将每个文件名设置为新变量,以便以后可以使用这些变量。

var1=file1
var2=file2
var3=file3

此外,如果有 X 数量的 .txt 文件,则意味着必须创建 X 数量的变量。所以在这个例子中,如果只有 3 个文件,则创建 3 个变量。

标签: windowsbatch-file

解决方案


这是一种方法,包括Rem方舟:

@Echo Off
Rem Localize variables, and enable extensions.
Rem  (needed for the Set, SetLocal, EndLocal, If, For, and GoTo commands).
SetLocal EnableExtensions
Rem Undefine any existing variables with names beginning with the $ character.
For /F "Delims==" %%G In ('Set $ 2^>NUL') Do Set "%%G="
Rem Define and count individual incrementing variables for each matching basename.
For /F "Tokens=1,* Delims=:" %%G In ('%__AppDir__%where.exe .:*.txt 2^>NUL^
 ^|%__AppDir__%findstr.exe /N "^"') Do Set "$%%G=%%~nH" & Set "#=%%G"
Rem Provide some feedback if no matches, and end the script after 3 seconds.
If Not Defined # (Echo There were no matching files
    %__AppDir__%timeout.exe /T 3 /NoBreak >NUL
    GoTo :EOF)
Rem Provide feedback on the number of matches.
Echo There were %#% matching files defined as variables.
Rem Ask end user if they would like to view the variables with their values.
Choice /M "Would you like to see them"
Rem If Yes, show them.
If %ErrorLevel% Equ 1 (SetLocal EnableDelayedExpansion
    For /L %%G In (1,1,%#%) Do Echo %%$%%G%% = !$%%G!
    EndLocal & Pause)
Rem Rest of your code goes below here.

推荐阅读