Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for string within filename in subdirectories

I have a large directory of folders (call it C:\Main). I need to set up a batch script to search the subfolders of that directory for a string within the filename (not the text within the file). I'm having trouble finding an answer.

Essentially, let's say I need to search for the string "abcd" within all the filenames in C:\Main\*. I'm only looking for matches that are a XML file. So I need to find:

C:\Main\Secondary1\abcd_othertext.xml

C:\Main\Secondary2\abcd_othertext.xml

C:\Main\Secondary3\abcd_othertext.xml

among all the hundreds of folders in that Main directory. Then I need to output all matches (ideally to individual variables in a bat file, but that's a different can of worms). Thanks in advance for your help.

like image 912
Ikarian Avatar asked Apr 25 '13 20:04

Ikarian


2 Answers

The DIR command can perform a wildcard search in subdirectories.

DIR abcd*.xml /s /b
like image 97
Tall Software Dude Avatar answered Nov 03 '22 08:11

Tall Software Dude


You can use a For /R loop: http://ss64.com/nt/for_r.html

@Echo OFF

Set "Pattern=abcd"

For /R "C:\" %%# in (*.xml) Do (
    Echo %%~nx# | FIND "%Pattern%" 1>NUL && (
        Echo Full Path: %%~#
        REM Echo FileName : %%~nx#
        REM Echo Directory: %%~p#
    )
)

Pause&Exit

EDIT: ...To individually variables:

@Echo OFF

Set "Pattern=abcd"

For /R "C:\" %%# in (*.xml) Do (
    Echo %%~nx# | FIND "%Pattern%" 1>NUL && (
        Set /A "Index+=1"
        Call Set "XML%%INDEX%%=%%~#"
        Echo Full Path: %%~#
        REM Echo FileName : %%~nx#
        REM Echo Directory: %%~p#
    )
)

CLS
Echo XML1 = %XML1%
Echo XML2 = %XML2%

Pause&Exit
like image 32
ElektroStudios Avatar answered Nov 03 '22 10:11

ElektroStudios