0

I have filenames like this:

M0654871_07_05_2011.pdf
M0654871_07_15_2011.pdf

Where 07_05_2011 is the date (MM_DD_YYYY) and the first number after M is just a "random" number.

I am writing a .bat file that loops over all the files in that directory. I want the script to count files on each day (based on the filename, not date modified).

It doesn't seem like there is any regex in batch scripting. Is there a way to accomplish this in Windows .bat scripting without downloading more tools/software?

(I could probably do a hard loop of checking the string against every single filename string for each day, but that is a bit much considering there are 10k+ files).

I found findstr can do regex in a way, but is there a way to use it to loop over the files and pull out number of files per date, instead of looping over dates and pulling out number of files?

JBurace
  • 5,123
  • 17
  • 51
  • 76

1 Answers1

1

There is nothing in FINDSTR to do what you want directly, but it is easy to do with a FOR loop coupled with an expansion substring and SET arithmetic.

The following code (without FINDSTR) may be good enough, depending on what other files may exist in the directory (not tested, but should work unless I let a silly bug slip through). The code works by creating a count variable with a name based on the date within the file name.

@echo off
setlocal enableDelayedExpansion
for %%F in (M*_??_??_????.pdf) do (
  set "fname=%%~nF"
  set /a fileDate_!fname:~-10!+=1
)
set fileDate_

If you want to more precisely look for valid dates in the last 10 characters of the name, then you can pipe the output of DIR to a FINDSTR regex. (again untested)

@echo off
setlocal enableDelayedExpansion
for /f %%F in ('dir /b M*_??_??_????.pdf ^| findstr /lixc:"M[0-9]*_[01][0-9]_[0-3][0-9]_[0-9][0-9][0-9][0-9]') do (
  set "fname=%%~nF"
  set /a fileDate_!fname:~-10!+=1
)
set fileDate_

The regex is not precisely restricting itself to valid dates, but most likely it is adequate. You may be able to be more precise using multiple regex search strings, but the severe limitations of FINDSTR will make it more difficult than it ought to be (see What are the undocumented features and limitations of the Windows FINDSTR command?)

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390