如何使用for循环遍历目录中的每个文件?

我如何判断某个条目是一个目录还是一个文件?


当前回答

从命令行运行FOR和从批处理文件运行FOR之间有细微的区别。在批处理文件中,您需要在每个变量引用前放置两个%字符。

从命令行:

FOR %i IN (*) DO ECHO %i

从批处理文件:

FOR %%i IN (*) DO ECHO %%i

其他回答

试试这个:

::Example directory
set SetupDir=C:\Users

::Loop in the folder with "/r" to search in recursive folders, %%f being a loop ::variable 
for /r "%SetupDir%" %%f in (*.msi *.exe) do set /a counter+=1

echo there are %counter% files in your folder

它会计算目录(以及子目录)中的。msi和。exe文件。因此,作为可执行文件的文件夹和文件之间也有区别。

如果需要过滤循环中的其他文件,只需添加一个扩展名(.pptx .docx ..)

遍历…

...当前目录下的文件:for %f in (.\*) do @echo %f ...subdirs in current dir: for /D %s in (.\*) do @echo %s .../R %f在(.\*)做@echo %f .../R /D %s in (.\*) do @echo %s

不幸的是,我没有找到同时遍历文件和子dirs的任何方法。

只需使用cygwin及其bash即可获得更多功能。

除此之外:你有没有注意到,MS Windows的内置帮助是描述cmd命令行的语法的一个很好的资源?

也可以在这里看看:http://technet.microsoft.com/en-us/library/bb490890.aspx

在我的情况下,我必须删除临时文件夹下的所有文件和文件夹。这就是我最后做这件事的原因。我必须运行两个循环一个文件和一个文件夹。如果文件或文件夹名称中有空格,则必须使用" "

cd %USERPROFILE%\AppData\Local\Temp\
rem files only
for /r %%a in (*) do (
echo deleting file "%%a" ...
if exist "%%a" del /s /q "%%a"
)
rem folders only
for /D %%a in (*) do (
echo deleting folder "%%a" ...
if exist "%%a" rmdir /s /q "%%a"
)

要遍历每个文件,可以使用for循环:

(目录\路径\*)do (something_here)

在我的例子中,我还需要文件内容、名称等。

这导致了一些问题,我认为我的用例可能会有所帮助。下面是一个循环,它从目录中的每个“。txt”文件中读取信息,并允许你对它做一些事情(例如setx)。

@ECHO OFF
setlocal enabledelayedexpansion
for %%f in (directory\path\*.txt) do (
  set /p val=<%%f
  echo "fullname: %%f"
  echo "name: %%~nf"
  echo "contents: !val!"
)

*限制:val<=%%f将只获得文件的第一行。

我会使用vbscript (Windows脚本主机),因为在批处理中,我确信你不能区分一个名称是一个文件还是一个目录。

在vbs中,它可以是这样的:

Dim fileSystemObject
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")

Dim mainFolder
Set mainFolder = fileSystemObject.GetFolder(myFolder)

Dim files
Set files = mainFolder.Files

For Each file in files
...
Next

Dim subFolders
Set subFolders = mainFolder.SubFolders

For Each folder in subFolders
...
Next

检查MSDN上的FileSystemObject。