Batch File folder detection

2019-08-10 21:03发布

问题:

Yes, I know I need to double-up the %a to be %%a when used in a batch file. ;)

This works, but does not give me the results I want - this is just too much..

FOR /f %a IN ('dir "D:\tomcat*" /ad /b ')  DO FOR /f %b IN ('dir "D:\%a\webapps" /ad /b ') DO ECHO D:\%a\webapps\%b

What I would really like to do is:

FOR /f %a IN ('dir "D:\tomcat*\webapps" /ad /b ')  DO ECHO %a

But, I get the resulting error:

The filename, directory name, or volume label syntax is incorrect.

I would like to do this as I have a need to detect which folders have tomcat in them and could be any of the following:

D:\tomcat
D:\tomcat1
D:\tomcat2
D:\tomcat_1
etc.

Thanks!

回答1:

you could use IF EXIST

FOR /f %a IN ('dir "D:\tomcat*" /ad /b ')  DO IF EXIST "%~a\webapps\nul" dir /b "%~a\webapps"

\nul is to check if folder exist.



回答2:

Wildcards (? and *) can only be used in the last item of a path, so you will have to work around that.

As an alternative method to the nested for loops you are using, you could also do the following:

for /F "eol=| delims=" %A in ('dir /A:D /B "D:\tomcat*"') do (> nul 2>&1 dir /A:D "%~A\webapps" && echo "%~A")

This outputs all folders whose names contain tomcat in their names and have got a subdirectory called webapps.

You need to provide the option string "eol=| delims=" for for /F; this also applies to the variant with the two nested for loops.