批处理如何识别文件夹中的文本文件并存储其文件名?

时间:2015-07-20 03:18:30

标签: windows batch-file cmd

我有一个名为newfolder的文件夹,文件夹中有abc.txt和def.txt。如何使用批处理将文件名abc.txtdef.txt存储到%file1%和%file2%中? .cmd将与newfolder位于同一目录中。

2 个答案:

答案 0 :(得分:1)

如果您只想将文本abc.txtdef.txt分配给变量,请使用:

set file1=abc.txt
set file2=def.txt

但我从你的问题中假设你要遍历文件。如果您明确希望abc.txt位于变量file1中且def.txt位于file2中,请使用:

@echo off
for %%f in (*) do (
  if %%f==abc.txt set file1=abc.txt
  if %%f==def.txt set file2=file.txt
) else (
  rem process other files
)

如果您只想将文件夹中的每个文本文件分配给变量,我建议设置一个计数器并使用它来设置文件变量:

@echo off
setlocal EnableDelayedExpansion
set num=0
for /f %%f in ('dir /b /s') do (
  set /a num+=1
  set file!num!=%%f
)

rem now process it as you wish. example:

echo !file1!
echo !file2!
echo !file3!
echo !file4!
echo !file5!
echo !file6!

pause

答案 1 :(得分:0)

set file1=abc.txt
set file2=def.txt