This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
42} What is the (sub)routine for testing a filename for wildcards?
Based on the comment given in the thread referred to in the "
References/Comments " at the and of this item
@echo off & setlocal enableextensions
set filename_="My * file"
echo %filename_%|findstr "[*?]">nul
if %errorlevel% EQU 0 (
echo %filename_% contains wildcards
) else (
echo No wildcards in %filename_%)
endlocal & goto :EOF
Note
that this also could be written as
@echo off & setlocal enableextensions
set filename_="My * file"
echo %filename_%|findstr "[*?]">nul ^
&& echo %filename_% contains wildcards^
|| echo No wildcards in %filename_%
endlocal & goto :EOF
The output would obviously be
C:\_D\TEST>cmdfaq
"My * file" contains wildcards
Another take, written with a subroutine and FIND instead of FINDSTR.
@echo off & setlocal enableextensions
::
:: Demo
set filename_=My * file
call :IsWildSub "%filename_%" isWild
if "%isWild%"=="yes" (
echo "%filename_%" contains wildcards
) else (
echo No wildcards in "%filename_%")
::
set filename_=My file
call :IsWildSub "%filename_%" isWild
if "%isWild%"=="yes" (
echo "%filename_%" contains wildcards
) else (
echo No wildcards in "%filename_%")
endlocal & goto :EOF
::
:: =====================================================
:: Does a name contain wildcards * and/or ?
:IsWildSub
setlocal enableextensions
echo %1|find "*">nul
if %errorlevel% EQU 0 (endlocal & set %2=yes& goto :EOF)
echo %1|find "?">nul
if %errorlevel% EQU 0 (endlocal & set %2=yes& goto :EOF)
endlocal & set %2=no& goto :EOF
For another example see IsWild in
Item #18.
There is a somewhat unrelated aside to wildcards in MS scripting which
differs from the usage which UNIX users in particular are accustomed to.
Consider a folder containing the following files.
a.txt
ab.txt
abc.txt
abcd.txt
As expected
dir /b *.txt
will give
a.txt
ab.txt
abc.txt
abcd.txt
however,
dir /b ??.txt
will give
a.txt
ab.txt
i.e. the
?? will match both one and two characters.
If one wishes to match exactly two characters, then one has to use
something like
dir /b "C:\_M\??.txt"|findstr /i "..\.txt"
which will give
ab.txt
What about two or more characters?
dir /b "C:\_M\*.txt"|findstr /i "..\.txt"
which will give
ab.txt
abc.txt
abcd.txt