批处理文件:从目录中读取文件名并存储在阵列中 [英] Batch File : Read File Names from a Directory and Store in Array

查看:75
本文介绍了批处理文件:从目录中读取文件名并存储在阵列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个批处理文件,其中需要列出指定文件夹的所有文本文件名,然后存储并从数组中检索相同的文件名.批处理文件中可能吗?我当前列出测试文件的代码如下

I'm creating a batch file in which I need to list all the text file name of the specified folder then store and retrieve the same from an array. Is it possible in Batch Files? My current code to list the test files is as below

 dir *.txt /b

非常感谢您的帮助.

推荐答案

模拟数组

字符串是批处理文件中唯一的变量类型.但是,可以使用多个具有相同名称的变量来模拟数组,但结尾的数字ID除外,例如:

String is the only variable type in batch file. However, arrays can be simulated with several variables of identical name except a trailing numerical ID such as:

Array[1]    Array[2]    Array[3]    Array[4]     etc...

我们可以将每个文件名存储到这些变量中.

We can store each file name into these variables.

检索命令输出

第一步是将命令输出放入变量中.我们可以使用for /f循环.

The first step is to put the command output into a variable. We may use the for /f loop.

for /f %%G in ('dir *.txt /b') do set filename=%%~G

('')子句和/f选项指定收集命令输出.请注意,由于变量覆盖,您获得的文件名始终是最后显示的文件名.可以通过追加来解决,但这超出了此答案的范围.

The ('') clause and /f option specifies to collect the command output. Note that the filename you get is always the last one displayed because of variable-overwriting. This can be resolved by appending instead, but is beyond the scope of this answer.

为文件提供ID

在这种情况下,我将用尾随ID [n]命名数组filename,其中n是数字ID.

In this case, I will name the array filename with a trailing ID [n], where n is a numerical 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="添加到循环中,以确保它可以与默认定界符一起正常工作.

  • I have added "delims=" into the loop to ensure it works properly with default delimiters.

我将%ID%替换为!ID!,因为已延迟扩展.简而言之,当禁用延迟扩展时,整个for循环在运行时之前被加上短语,具有新值的变量不会更新为block(())结构;如果启用,则将更新所述变量. !ID!表示需要在每个循环中进行更新.

I replaced %ID% with !ID! because of delayed expansion. In short, when delayed expansion is disabled, the entire for loop is phrased before runtime, variables with new values are not updated block(()) structures; if enabled, the said variables are updated. !ID! indicates the need for update in each loop.

这篇关于批处理文件:从目录中读取文件名并存储在阵列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆