?
Solved

Find file count in a dir given specific file pattern

Posted on 2010-01-12
16
Medium Priority
?
642 Views
Last Modified: 2012-05-08
Hi:

   I need to find the count of files in a dir given specific file pattern. So far I have the below code that executes a do loop for every file  found of the specified pattern. I would like the do portion not to execute if the file count is 0.

set filepattern=%MyDir%\Product_*_week.sas

for /F "tokens=* delims=" %%a in ('dir /b /a-d "%filepattern%"^|sort') do (
  foreveryfileDoThis()
 }
0
Comment
Question by:LuckyLucks
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 4
  • +1
16 Comments
 
LVL 56

Expert Comment

by:Bill Prew
ID: 26294638
That should be the case based on what you have, if there are no matching files you won't get into the loop body.

~bp
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 26294651
It shouldn't run anyway.  Without any output from the dir command the do loop won't come into it.

Steve
0
 
LVL 56

Expert Comment

by:Bill Prew
ID: 26294660
If you are getting into the loop body try the following and see what files are making it in: (I also noticed your last paren was a brace in your example, is that just a typo on the posting here?)

set filepattern=%MyDir%\Product_*_week.sas
for /F "tokens=* delims=" %%a in ('dir /b /a-d "%filepattern%"^|sort') do (
  echo %%a
  foreveryfileDoThis()
 )

~bp
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
LVL 43

Assisted Solution

by:Steve Knight
Steve Knight earned 400 total points
ID: 26294674
You might aswell use dir /one too rather than piping through sort as this introduces a temporary file and slight delay.
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 26295048
Sorry cross posted there Bill.  if you do actually what to find the file count then you can use find /c btw:

for /f %%a in ('dir /b /a-d ^| find /v "xxx" /c') do set count=%%a

Steve
0
 

Author Comment

by:LuckyLucks
ID: 26296129
I think in the absence of any files in the dir that match the pattern, it still executes the do loop or something because it returns the File Not Found error

C:\MyDir>for /F "tokens=* delims=" %a in ('dir /b /a-d "C:\MyDir\blah.txt"') do
(
 echo %a
)
File Not Found
0
 
LVL 56

Accepted Solution

by:
Bill Prew earned 800 total points
ID: 26296193
Yes, that's the "error" from DIR when no files are found.  But it's going to STDERR, not STDIN, so it won't execute the DO logic.  Try this instead:

for /F "tokens=* delims=" %a in ('dir /b /a-d "C:\MyDir\blah.txt" 2^>NUL') do( echo %a)

~bp
0
 
LVL 56

Expert Comment

by:Bill Prew
ID: 26296202
The 2>NUL sends any STDERR output to the NUL device so it doesn't display on the screen...

~bp
0
 
LVL 16

Assisted Solution

by:t0t0
t0t0 earned 800 total points
ID: 26298032
LuckyLucks

The following line will display a filecount of your %filepatter%:

   dir /a-d /b "%filepattern%" 2>nul | find /v "" /c


So, to get the count into a variable, you could do this:

   for /f %%a in ('dir /a-d /b "%filepattern%" 2^>nul | find /v "" /c') do set count=%%a


If all you want is to do is run some code ONLY if there are certain files present then all you need to do is:

   dir /a-d "%filepattern%" >nul 2>&1

   if %errorlevel%=0 (
      echo Matching files found
   ) else (
      echo No matching files found
   )


Now, if you want to process each matching file, but do nothing if no files are found, then this would normally do the job:

   set filepattern=Product_*_week.sas

   for /f "tokens=*" %%a in ('dir /a-d /b "%MyDir%\%filepattern%" 2^>nul') do (
      process "%MyDir%\%%a"
   )

NOTE: I have removed %MyDir% from %filepattern% and inserted it in the carrect places in the FOR loop.

0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 26298783
t0t0, that it just repeating what has already been said by billprew and myself.
0
 
LVL 16

Expert Comment

by:t0t0
ID: 26299879
dragon-it

I STRONGLY disagree with your last comment - I am NOT repeating what you and billprew wrote.

I suggest you have a CLOSER look at my code.

Neither of you have shown code which uses %errorlevel%. Nor code which uses the IF-ELSE statement.

Please do not try to discredit me although, I have rechecked my code and noticed a few minor typing errors so I will post again.
0
 
LVL 16

Expert Comment

by:t0t0
ID: 26300032
LuckyLucks

    Due to a few minor (but significant) typing errors I am commenting again.



DISPLAY NUMBER OF MATCHING FILES

    The following line will display a filecount of your %filepatter%:

    dir /a-d /b "%filepattern%" 2>nul | find /v "" /c



GETTING THE FILECOUNT INTO A VARIABLE

    So, to get the count into a variable, you could use one of these methods:


    METHOD 1:

    Using DIR's standard output with FIND to filter "File(s)"

    for /f %%a in ('dir /a-d %filepattern% ^|find "File(s)"') do set count=%%a
    echo %count%


    METHOD 2:

    Using FIND's count parameter

    for /f %%a in ('dir /a-d /b "%filepattern%" 2^>nul ^| find /v "" /c') do set count=%%a
    echo %count%



CONDITIONAL PROCESSING

    PROCESS CODE

    If you want to run some code ONLY if certain files exist, you need to use DIR with ERRORLEVEL:

    dir /a-d "%filepattern%" >nul 2>&1
    if %errorlevel%==0 (
       echo Matching files found
    ) else (
       echo No matching files found
    )


    PROCESS FILES

    If you want to process files ONLY if they exist, then you need to use FOR like this:

   for /f "tokens=*" %%a in ('dir /a-d /b "%filepattern%" 2^>nul') do (
      echo Process "%%a"
   )



NOTE:

There are unavoidable similarities between my code and code written by both billprew and dragon=it however, this is purely accidental.
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 26301028
t0t0, I wasn't suggesting you were copying what we had written, I know you can write such code of course.  Just that there were already answers there that gave what was needed - was just a question, not intending to annoy you.

In any case billprew's original suggestion IMO is best in that it reads the dir command and processes the do loop once in the for command and if the file count is 0 then it doesnt run the loop.

In fact aside from a } instead of ) which was probably only a typo entering it here anyway the original posters code is fine already, aside from the fact that it prints "file not found" to the screen via STDERR if there are none so there is no need to find the number of files in the dir anyway unless the asker actually needs it elsewhere.

Steve
0
 
LVL 16

Expert Comment

by:t0t0
ID: 26301711
You wrote:

    >>"In any case billprew's original suggestion IMO is best ...."

Nonsense! In his first comment he writes:

    >>"for /F "tokens=* delims=" %%a in ('dir /b /a-d "%filepattern%"^|sort') do ("

What the hell is the SORT doing in there?

Furthermore, he wrote:

    >>"for /F "tokens=* delims=" %a in ('dir /b /a-d "C:\MyDir\blah.txt" 2^>NUL') do"

This is not even proper code. It's more like pseudocode with the "C:\MyDir\blah.txt". Furthermore, what the hell is "delims=" doing in there?

billprew has come a long way from nowhere. I have seen his ranking rise at a furious rate however, I fear this may have been at the expense of good (and original) code. Don't forget, we're supposed to be EXPERTS - even thugh I admit to getting it wrong at times too - like my earlier comment.

I MUST stress quite emphatically that my final code is the BETTER solution. This is:

   for /f "tokens=*" %%a in ('dir /a-d /b "%filepattern%" 2^>nul') do (
      echo "%%a"
   )
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 26302308
t0t0,  

I'll leave this Q now to LuckyLucks, I know you get a bee in your bonnet about code being "correct".  BUT there is no need to change the askers code at all http:#26294638 and http:#26294638 posted by Bill and myself at the same time say this, and I'm sure that you must agree.

It is of course possible to re-write the code in a different way, and we can hide the STDERR "file not found" but it does not effect the operation of the command at all.  But as it stans LuckyLucks code works already.  I would just add /one to the dir like I suggested rather than using ^|sort and add a hide the STDERR output.

An expert needs to know sometimes that if someone says "how can I do..." then the answer "it already does" is surely as acceptable as providing altenative code IMO.

Steve
0
 
LVL 16

Expert Comment

by:t0t0
ID: 26305180
You make a good point and I will consider the merits of that last comment.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Using dates in 'DOS' batch files has always been tricky as it has no built in ways of extracting date information.  There are many tricks using string manipulation to pull out parts of the %date% variable or output of the date /t command but these r…
VALIDATING DATES One method of validating dates is to jam the date into the DATE command and see if it accepts it by examining the system's errorlevel value. A non-zero result indicates failure. A typical example might look something like the fol…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question