如何获得的文件名列表中的一个目录,并使用CMD命令存储在一个变量 [英] How to get the list of filenames in a directory and store that in a variable using cmd commands

查看:252
本文介绍了如何获得的文件名列表中的一个目录,并使用CMD命令存储在一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让所有的文件名中的一个目录,并将它们存储在从命令行一些变量。

I need to get all the filenames in a directory and store them in some variable from a command line.

我碰到这个来

`dir /s /b > print.txt`

但这种打印的文件名到一个txt文件。

but this prints the file names to a txt file.

我怎么能这些名称存储在一个变量?

How can I store these names in a variable?

推荐答案

我假设你真的是Windows批处理文件,而不是DOS。

I'm assuming you really mean Windows batch file, not DOS.

批处理环境变量被限制为8191个字符,所以有可能将不能够对所有的文件路径放入一个变量,这取决于文件的数量和文件的平均路径长度

Batch environment variables are limited to 8191 characters, so likely will not be able to fit all the file paths into one variable, depending on the number of files and the average file path length.

文件名应的情况下,它们包含空格被引用。

File names should be quoted in case they contain spaces.

假设他们融入一个变量,你可以使用:

Assuming they fit into one variable, you can use:

@echo off
setlocal disableDelayedExpansion
set "files="
for /r %%F in (*) do call set files=%%files%% "%%F"

CALL语句是相当缓慢的。这是更快地使用延迟扩展,但扩张%%˚F将损坏任何包含值​​如果拖延扩张启用。随着更多的工作,你可以有一个快速和安全的延迟扩展版本。

The CALL statement is fairly slow. It is faster to use delayed expansion, but expansion of %%F will corrupt any value containing ! if delayed expansion is enabled. With a bit more work, you can have a fast and safe delayed expansion version.

@echo off
setlocal disableDelayedExpansion
set "files=."
for /r %%F in (*) do (
  setlocal enableDelayedExpansion
  for /f "delims=" %%A in ("!files!") do (
    endlocal
    set "files=%%A "%%F"
  )
)
(set files=%files:~2%)

如果文件名不符合一个变量,那么你应该诉诸值的伪数组,每个文件之一。在下面的脚本中,我使用FINDSTR至preFIX DIR ouptut的每一行的行号preFIX。我用行号为索引到阵列

If the file names do not fit into one variable, then you should resort to a pseudo array of values, one per file. In the script below, I use FINDSTR to prefix each line of DIR ouptut with a line number prefix. I use the line number as the index to the array.

@echo off
setlocal disableDelayedExpansion
:: Load the file path "array"
for /f "tokens=1* delims=:" %%A in ('dir /s /b^|findstr /n "^"') do (
  set "file.%%A=%%B"
  set "file.count=%%A"
)

:: Access the values
setlocal enableDelayedExpansion
for /l %%N in (1 1 %file.count%) do echo !file.%%N!

这篇关于如何获得的文件名列表中的一个目录,并使用CMD命令存储在一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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