• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 651
  • Last Modified:

Find file count in a dir given specific file pattern

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
LuckyLucks
Asked:
LuckyLucks
  • 6
  • 5
  • 4
  • +1
3 Solutions
 
Bill PrewCommented:
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
 
Steve KnightIT ConsultancyCommented:
It shouldn't run anyway.  Without any output from the dir command the do loop won't come into it.

Steve
0
 
Bill PrewCommented:
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
[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

 
Steve KnightIT ConsultancyCommented:
You might aswell use dir /one too rather than piping through sort as this introduces a temporary file and slight delay.
0
 
Steve KnightIT ConsultancyCommented:
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
 
LuckyLucksAuthor Commented:
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
 
Bill PrewCommented:
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
 
Bill PrewCommented:
The 2>NUL sends any STDERR output to the NUL device so it doesn't display on the screen...

~bp
0
 
t0t0Commented:
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
 
Steve KnightIT ConsultancyCommented:
t0t0, that it just repeating what has already been said by billprew and myself.
0
 
t0t0Commented:
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
 
t0t0Commented:
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
 
Steve KnightIT ConsultancyCommented:
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
 
t0t0Commented:
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
 
Steve KnightIT ConsultancyCommented:
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
 
t0t0Commented:
You make a good point and I will consider the merits of that last comment.
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 6
  • 5
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now