Search code examples
batch-filesubstringstring-comparison

Check if a line from a txt file is a substring of a filename using batch


i have a txt file with several lines, now i want to check if a line is a substring of a filename. this is my code so far

for /r D:\ %%y in (*.*) do (
    for /f %%x in (list.txt) do (
        echo %%y|find %%x >nul
        if errorlevel 1 (echo notfound) else (echo found)
                )
        )

the first loop gets the filename while the second loop gets the lines from the txt file. now i know that the format for FIND is wrong as you need to define the string that you want to find but i want to show what i want to achieve. i want to check if %%y contains %%x. so how do i achieve that? thank you for any suggestions and sorry if my explanation is a bit hazy :D


Solution

  • @ECHO OFF
    SETLOCAL
    FOR /f "delims=" %%k IN (filename.txt) DO DIR /s /a-d *%%k* 2>NUL >NUL &IF ERRORLEVEL 1 (ECHO %%k NOT found) ELSE (ECHO %%k found)
    

    Read each line from the file. Perform a dir trying to find that filename anywhere in the subtree (/s for subdirectories, /a-d for no directorynames, 2>nul to suppress file not found messages, >nul to suppress the report) setting errorlevel 0 for found and non-0 for not found.