如果pest
是根立即子目錄(即當前目錄,.
),你可以做到以下幾點:
rem // Enumerate immediate child files in the root, output them:
> "temp1.txt" (for %%F in (".\*.f") do @echo %%~fF)
rem // Enumerate immediate subdirectories of the root:
>>"temp1.txt" (
for /D %%D in (".\*.*") do @(
rem // Skip the rest if current subdirectory is the one to exclude:
if /I not "%%~nxD"=="pest" (
rem // Output all files found in the current subdirectory recursively:
pushd "%%~D"
for /R %%E in ("*.f") do @echo %%~E
popd
)
)
)
這僅返回文件,但沒有目錄;如果你想這樣被列入過,請嘗試以下代碼:
rem // Output the path to the root directory itself:
> "temp1.txt" (for /D %%D in (".") do @echo %%~fD)
rem // Enumerate immediate child files in the root, output them:
>>"temp1.txt" (for %%F in (".\*.f") do @echo %%~fF)
rem // Enumerate immediate subdirectories of the root:
>>"temp1.txt" (
for /D %%D in (".\*.*") do @(
rem // Skip the rest if current subdirectory is the one to exclude:
if /I not "%%~nxD"=="pest" (
rem // Output the current subdirectory:
echo %%~fD
rem // Output all files found in the current subdirectory recursively:
for /F "eol=| delims=" %%E in ('dir /B /S "%%~D\*.f"') do @echo %%E
)
)
)
如果pest
子目錄可以在樹中的任何地方,你可以使用這種方法:
@echo off
rem /* Call subroutine with the root directory (the current one), the file pattern
rem and the name of the directory to exclude as arguments: */
> "temp1.txt" call :SUB "." "*.f" "pest"
exit /B
:SUB val_dir_path val_file_pattern val_dir_exclude
rem // Output directory (optionally):
echo %~f1
rem // Enumerate immediate child files and output them:
for %%F in ("%~1\%~2") do echo %%~fF
rem // Enumerate immediate subdirectories:
for /D %%D in ("%~1\*.*") do (
rem // Skip the rest if current subdirectory is the one to exclude:
if /I not "%%~nxD"=="%~3" (
rem /* Recursively call subroutine with the current subdirectory, the file pattern
rem and the name of the directory to exclude as arguments: */
call :SUB "%%~D" "%~2" "%~3"
)
)
爲了避免子目錄也要輸出,只需刪除命令行echo %~f1
即可。
由於此方法具有遞歸子程序調用,因此在沒有pest
子目錄的情況下,性能明顯比使用簡單的dir /S
命令差。
將'DIR'命令的結果傳遞給'FIND'命令,並使用/ V選項和'FIND'命令。 – Squashman
@Squashman,這並不妨礙'dir/S'列舉目錄,這是問題的意圖,據我所知... – aschipfl