hogo
hogo

Reputation: 3

How to check if a filename with specific pattern exists in cmd batch script?

How to use [0-9] in if exist statement. I want to check a file with second digit is 1-9 exist or not.

If exist "filepath\\a[1-9]*" (echo "yes")

It seems [1-9] wildcard does not work in if exist statement.

Do you have any idea how to implement this check?

e.g. print "yes" when a file named a1 (a2da) exists, but not a0 (a0ss)

Upvotes: 0

Views: 1045

Answers (4)

Stephan
Stephan

Reputation: 56180

The one and only command in cmd that supports (a crippled version of) REGEX is findstr. So you can use that to complete your task:

dir /a-d "%filepath%\a*" | findstr /ib "a[123456789].*" >nul && echo yes || echo no

Note, this will also find files like a12anything.txt and A2anything.txt but not a0anything.txt.

Upvotes: 0

Compo
Compo

Reputation: 38623

As this is a batch file, and is only written once, there's little need to try to make your command as short as possible. Therefore just use one dir command and one echo command, instead of the currently accepted answer which essentially runs ten if commands, potentially nine set commands, and one echo command.

@Dir "filepath\a1*" "filepath\a2*" "filepath\a3*" "filepath\a4*" "filepath\a5*" "filepath\a6*" "filepath\a7*" "filepath\a8*" "filepath\a9*" /B /A:-D 2>NUL 1>&2 && Echo Yes

As filepath is constant, you could even do it like this:

@CD /D "filepath" 2>NUL && (Dir a1* a2* a3* a4* a5* a6* a7* a8* a9* /B /A:-D 2>NUL 1>&2 && Echo Yes)

Please note however, that your question is not clear enough to determine your full task. This example will print Yes if a[123456789]… exists in filepath, it will do that regardless of whether a file named a0… also exists in filepath.

Upvotes: 0

yonni
yonni

Reputation: 352

If you only check the second character, without considering the other characters after it, you can use something like this:

for /l %%n in (1,1,9) do if exist "a%%n*" set "ANS=%%n"
if defined ANS echo yes

Upvotes: 2

lit
lit

Reputation: 16236

Another way to do this would be to use PowerShell. If you are on a supported Windows system it is already installed.

powershell -NoLogo -NoProfile -Command "Test-Path -Path '.\a[1-9]*'"

Upvotes: 0

Related Questions