Search for a string in a file name in subdirectories

I have a large folder directory (name it C: \ Main). I need to configure a script package to search for subfolders of this directory for a string inside a file name (and not text inside a file). I am having trouble finding an answer.

Essentially, let's say I need to find the string "abcd" in all the file names in C: \ Main \ *. I am only looking for matches that are XML files. Therefore, I need to find:

C: \ Main \ Secondary1 \ abcd_othertext.xml

C: \ Main \ Secondary2 \ abcd_othertext.xml

C: \ Main \ Secondary3 \ abcd_othertext.xml

among all hundreds of folders in this main directory. Then I need to output all matches (ideally, for individual variables in the bat file, but it could be another worm from worms). Thanks in advance for your help.

+5
source share
3 answers

The DIR command can search for wildcards in subdirectories.

DIR abcd*.xml /s /b
+12
source

You can use the 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: ... For individual 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
+5
source

ElektroStudios element with a fixed problem with spaces, backslashes, and a missing drive letter in print 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!"
    )
)
0
source

All Articles