user1229895
user1229895

Reputation: 2319

BAT script to search directory for folders that match an input name

not sure what's the best (or better) way to write a bat script to take name input and search a directory to see whether it exists.

do I need to output the directory list to a file first before running a comparison?

and if it makes a difference, the directory is on a repository so for my purposes I'll be using 'svn list', but I thought a nice general solution for everyone would be nice.

Upvotes: 1

Views: 12835

Answers (1)

dbenham
dbenham

Reputation: 130839

If you are testing for a specific name within a directory, then you would generally do something like:

if exist name (echo found it) else (echo not found)

Or if the name is incomplete

if exist *name* (echo found it) else (echo not found)

If you are testing for a name anywhere within a directory tree, then I would use

dir /s /a-d *name* >nul && (echo found it) || (echo not found)

If you are issuing a command that generates lines of output and you want to test if a name exists within any one line, then Windows pipes generally work fine, as long as the size of the output is not huge and the 2nd half can keep up with the 1st half.

yourCommand | find "name" >nul && (echo found it) || (echo not found)

But pipes become inefficient if the 2nd half is slow compared to the 1st half, and a lot of data must be buffered. In that case it is definitely better to use a temp file instead of a pipe. I incorporate a random number into the temp file name to guard against possible collision of multiple processes using the same temp directory.

set tempFile="%temp%\myTempFileBaseName%random%.txt"
yourCommand >%tempFile%
<%tempFile% find "name" >nul && (echo found it) || (echo not found)
del %tempFile%

I generally use pipes unless I know I have a performance issue.

Upvotes: 3

Related Questions