5

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.

Ikarian
  • 51
  • 2
  • 2
  • 4

3 Answers3

14

The DIR command can perform a wildcard search in subdirectories.

DIR abcd*.xml /s /b
5

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
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
0

ElektroStudios' anwser with fixed problem with spaces, backslashes and missing drive letter in printed directories:

@ECHO OFF
SETLOCAL enabledelayedexpansion

SET "pattern=abcd"
FOR /R "C:\" %%# in (*.xml) DO (
    ECHO %%~nx# | FIND "%pattern%" 1>NUL && (
        SET current_dir=%~d0%%~p#
        SET current_dir=!current_dir:\=/!

        ECHO Directory: "!current_dir!"
    )
)
user11153
  • 8,536
  • 5
  • 47
  • 50