Search file with wildcard path

假装没事ソ 提交于 2019-12-18 07:06:49

问题


I want to write a script to prompt user for file path and list all files found. The file path can contain wildcards. Something similar to this. But the batch script version of it. For example:

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

The files might be located like this:

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

I tried to use FOR and it turns out to be so much harder than expected because FOR does not support wildcards in the middle of a path.
Is there a way to list these files? (Maybe without using for?)


回答1:


I think this recursive solution works pretty well; you may name it 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

EDIT: I fixed a small bug in the last for /F command.

For example, the output of WCDIR.bat C:\Windows\Sys*\find*.exe command in my Windows 8.1 64-bits computer is:

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



回答2:


You can try with the command Where /?

The WHERE command is roughly equivalent to the UNIX 'which' command. By default, the search is done in the current directory and in the 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


来源:https://stackoverflow.com/questions/39599099/search-file-with-wildcard-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!