windows - 将每个文件名批量设置为不同的变量
问题描述
目录中有随机数量的具有相同扩展名的文件。
例如
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 个变量。
解决方案
这是一种方法,包括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.
推荐阅读
- python - 如何使用 django 中的输入表单从数据库中删除记录
- java - AES 解密 NodeJs 中的文件
- javascript - 如何使用纯 JAvaScript 制作 div resizer
- file - UWP如何访问文件夹中的文件
- ionic-framework - 在子页面上隐藏 IonTab - Ionic React 5
- go - 这两种声明方式的区别,一种有新的,一种没有?
- android - Android服务stopSelf()不停止服务
- c++ - 两个字命令命令 C++
- python - 使用许多熊猫列创建新列的字符串格式
- git - 如何将元数据信息添加到 git 提交