Batch file regular expression to find files with a digit in the name
Asked Answered
O

3

6

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?

Obnubilate answered 11/9, 2011 at 9:21 Comment(1)
What exact range are you after and what format are the file names in?Anana
A
11

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].

Anana answered 11/9, 2011 at 23:21 Comment(1)
Hi, one could get rid of the intermediate file Dir.temp by piping the output of dir /B to findstr. Like this dir /B | findstr /R "[0-9]" > FindStr.temp. Otherwise, a very good post, helped me a lot. Cheers!Hookah
L
2

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.

Leto answered 11/9, 2011 at 9:29 Comment(2)
Yes you guessed it I am talking about windows Batch I guessed that there is no such thing, but it doesn't hurt to ask Anyway thanks:)Obnubilate
Absolutely... powershell will defo do what you want though, and can be used in place of batch files.Leto
C
1

There is in findstr. Check out THIS

Condescension answered 11/9, 2011 at 9:35 Comment(2)
findstr only searches inside files for a given string, in this case I think the OP was on about command line regular expressions.Leto
And if you write a command output to a file, you can search it with findstr.Anana

© 2022 - 2024 — McMap. All rights reserved.