I want an example of a batch file that uses a regular expression to find files with a digit in the name or a certain range of numbers.
Is there a way to do this? A simple example?
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
So %%k refers to the value of the 3rd token, which is what is returned.
The %~dp0 (that's a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file. The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.
Some of this credit goes to Y.A.P.'s answer.
The following code will get you every file in the directory with at least one digit in the file name:
@Echo Off
CD C:\Folder\To\Process
Dir /B>Dir.temp
FindStr /R "[0-9]" "Dir.temp">FindStr.temp
Del Dir.temp
For /F "tokens=*" %%a In (FindStr.temp) Do Call :WorkIt "%%a"
Del FindStr.temp
Exit /B
:WorkIt
:: Insert code here. Use %1 to get the file name with quotes. For example:
Echo Processing %1...
Exit /B
The FindStr
line contains the regex expression. The Command Line version of regex is limited. What exact range are you after and what format are the file names in?
If, for example, you knew all files had 3 digit numbers in them, you could limit it to all items from 000 to 299 with the expression [0-2][0-9][0-9]
.
I'm assuming your on about Command Prompt / MS-Dos batch files here?
If you are then sadly the answer is NO, the ONLY wildcards that plain old batch files support are:
* = match all
and ? = Match 1
so:
mytune*.mp?
would match:
mytune01.mp3, mytune01.mpg, mytune-the-best.mpe
There is however an alternative...
If your using a modern windows version, then chances are you'll have power-shell installed, click on
start->run then type in power-shell and press return, if you get what looks like a command prompt window open then you have it installed, If not then look on the MS site for a download.
Once you have this, if you want to dive straight in, you can find all you need on Reg-ex is PS here:
http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-13-text-and-regular-expressions.aspx
I would however, recommend spending an hour or so learning the basics first.
There is in findstr. Check out THIS
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