使用通配符路径搜索文件

时间:2016-09-20 16:15:23

标签: batch-file path

我想编写一个脚本来提示用户输入文件路径并列出找到的所有文件。文件路径可以包含通配符。与this类似的东西。但它的批处理脚本版本。例如:

C:\Somewhere\user*\app\version-*.*\start.exe

文件可能如下所示:

C:\Somewhere\user345\app\version-1.0\start.exe
C:\Somewhere\user898\app\version-1.2\start.exe
C:\Somewhere\user898\app\version-1.3\start.exe

我尝试使用FOR,结果比预期的要困难得多,因为FOR在路径中间不支持通配符。
有没有办法列出这些文件? (也许没有使用for?)

2 个答案:

答案 0 :(得分:2)

我认为这种递归解决方案效果很好;你可以命名为 WCDIR.bat

@echo off
setlocal

if "%~1" neq "" set "next=%~1" & goto next
echo Show files selected by several wild-cards
echo/
echo WCDIR wildcardPath
echo/
echo Each folder in the path may contain wild-cards
echo the last part must be a file wild-card
goto :EOF

:next
for /F "tokens=1* delims=\" %%a in ("%next%") do set "this=%%a" & set "next=%%b"
if defined next (
   for /D %%a in ("%this::=:\%") do (
      setlocal
      cd /D "%%~a" 2>NUL
      if not errorlevel 1 call :next
      endlocal
   )
) else (
   for /F "delims=" %%a in ('dir /B /A:-D "%this%" 2^>NUL') do echo %%~Fa
)
exit /B

编辑:我在上一个for /F命令中修复了一个小错误。

例如,我的Windows 8.1 64位计算机中WCDIR.bat C:\Windows\Sys*\find*.exe命令的输出是:

C:\Windows\System32\find.exe
C:\Windows\System32\findstr.exe
C:\Windows\SysWOW64\find.exe
C:\Windows\SysWOW64\findstr.exe

答案 1 :(得分:0)

您可以尝试使用Where /?

命令

WHERE 命令大致相当于UNIX'which'命令。默认情况下,搜索在当前目录和PATH中完成。

    @echo off
    Where /R "%programfiles%" *winrar.exe
    pause
@echo off
:: Example d'input
set UserInput=*drive*

:: building the Pattern
set cmd=%Userinput%.exe

:: storage Where.exe command in a macro, the execution will be faster
set whereCmd=where.exe /r c:\windows\ %cmd%

:: execution of macro and output formatting
for /f %%a in ('%whereCmd%') do echo %%~nxa --^> %%a
pause
相关问题