0

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)

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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]*'"

Comments

0

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.

1 Comment

I edited my answer, and it does exactly what you ask.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.