I'm trying to use a batch file to list files in a directory such that the file name only (minus extension) matches only numeric patterns, e.g. something like 125646543.pdf which would be easy to express as a regex [\d]+\.pdf but of course I don't have such niceties with Windows-only mechanisms... I'm trying to do this with Windows-only mechanisms since I cannot install anything else on the target servers, and it needs to be supported at least on Windows Server 2000 and 2003.
I'll take a specific solution for this particular example or something more generic that has something more advanced than just ye olde * and ?
I've already tried to work with set /a in order to add a number to the file name, but since it interprets strings as environment variables and 0's if they're not defined, this doesn't work well. I also tried using if %%~na GTR 0, but that matches text file names such as report.pdf as well, since it seems to do a string comparison in this case.
findstr
can do regexes under Windows just fine. I'd try:
dir /b | findstr /i "^[0-9][0-9]*\.pdf$"
The "dir /b"
gives you the filenames only, one per line. The regex matches one or more digits followed by a period followed by your desired extension. For any extension, you could do:
dir /b | findstr "^[0-9][0-9]*\.[^\.]*$"
Obviously, if there are other cases more complicated, you can adjust the regex to suit. It doesn't have the full power of UNIX regexes but it's reasonably good.
The following command file shows how you can process each pdf file in the current directory that meets your "all-numeric" requirement.
@echo off
setlocal enableextensions enabledelayedexpansion
for /f "usebackq" %%i in (`dir /b ^| findstr /i "^[0-9][0-9]*\.PDF$"`) do (
set fspec=%%i
echo.Processing !fspec!
)
endlocal
The site http://www.robvanderwoude.com/batchfiles.php is a very good resource for CMD file magic (and many more things).
windows have provided you with an improved programming tool since win98. Its called vbscript.
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName = strFile.Name
strExtension = objFS.GetExtensionName(strFile)
strBase = objFS.GetBaseName(strFile)
If IsNumeric(strBase) Then 'check if numeric
WScript.Echo strBase
'continue to process file here.......
End If
Next
for more information on vbscript, read the manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With