Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search file with wildcard path

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?)

like image 480
wthe22 Avatar asked Nov 17 '25 15:11

wthe22


1 Answers

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
like image 69
Aacini Avatar answered Nov 20 '25 09:11

Aacini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!