如何仅将文本文件中列出的那些文件夹的文件和文件夹列表获取到列表文件中?

时间:2018-09-30 16:25:20

标签: batch-file cmd

我创建了一个批处理文件,以将指定目录中的所有文件,文件夹和子文件夹导出到文本文件。我需要的是从包含其路径的文本文件中列出带有子文件夹的特定文件。批处理文件将列出仅包含在此文本文件中的文件和子文件夹。例如,我只需要将这些文件夹下的文件导出到文本文件,就像输入文本文件一样。

C:\Users\Username\Documents\test1
C:\Users\Username\Documents\test2
C:\Users\Username\Documents\test3
C:\Users\Username\Documents\test4

谢谢。

已编辑以添加更多详细信息;通常,我们使用以下命令列出目录下的所有文件:

dir > output.txt

我想采用另一种方法。我只想在特定目录下列出文件,因为文本文件将包含这些特定目录路径。

这是文本文件:

C:\Users\Username\Documents\myfolder1
C:\Users\Username\Documents\myfolder2
C:\Users\Username\Downloads\yet another folder

尽管“文档和下载”中还有许多其他文件夹,但仅列出其路径在我的输入文本文件中列出的文件夹下的文件。然后,myfolder1myfolder2yet another folder的所有子文件夹和文件将被发送到输出文本文件。

2 个答案:

答案 0 :(得分:1)

读取一个包含文件夹名称的文件,并在每个文件夹及其子文件夹中列出列表文件:

@echo off
for /f "delims=" %%a in (file.txt) do dir /s /b "%%a\*"

根据需要调整dir开关和文件掩码。

答案 1 :(得分:0)

此非常简单的批处理文件可用于此任务:

@echo off
rem First check existence of folders list file and exit
rem batch file execution if this file does not exist.

if not exist "%UserProfile%\Documents\FoldersList.txt" goto :EOF

rem Delete output list file if already existing from a previous execution.
rem The error message output on file not existing is suppressed by
rem redirecting it from handle STDERR (standard error) to device NUL.

del "%UserProfile%\Documents\OutputList.txt" 2>nul

rem For each folder path in folders list file run the command DIR to output
rem in bare format all files and folders including hidden files and folders
rem in the folder and all its subfolders with redirecting the output written
rem to handle STDOUT (standard output) to the output list file with appending
rem the new lines at end of the list file. The list file is automatically
rem created on first line written to the output list file.

for /F "usebackq eol=| delims=" %%I in ("%UserProfile%\Documents\FoldersList.txt") do dir "%%~I\*" /A /B /S >>"%UserProfile%\Documents\OutputList.txt"

只需用/A替换 DIR 选项/A-D即可生成没有文件夹的文件列表,这意味着除属性目录外的任何属性。这与用于最后一个命令行相同,不同之处在于内部 FOR 不会输出具有隐藏属性集的文件:

for /F "usebackq eol=| delims=" %%I in ("%UserProfile%\Documents\FoldersList.txt") do for /R "%%~I" %%J in (*) do echo %%J>>"%UserProfile%\Documents\OutputList.txt"

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。

  • del /?
  • dir /?
  • echo /?
  • for /?
  • rem /?

另请参阅有关Using command redirection operators的Microsoft文章。