我目前在Windows批处理文件中使用以下行:
@ REM List all *.f in current dir and all its subdirs
dir *.f /B /S > temp1.txt
不幸的是,其中一个子目录(将其命名为pest
)具有非常大的子树,这使处理过程非常缓慢。由于pest
子目录对于此特定任务实际上并不重要(不应包含任何相关文件),因此我想将其从搜索中排除。
因此,我不想在当前目录和所有子目录中搜索,而是想在当前目录和除之外的所有子目录中搜索pest
。
您能提出一种简单的方法吗?
如果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
。
由于此方法具有递归子例程调用的功能,因此dir /S
在没有pest
子目录的情况下,性能明显比使用简单命令差。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句