Leptonator
Leptonator

Reputation: 3519

Looking for two strings for file names in Batch

This should be simple.. But, I am not getting it..

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /r "D:\12" %%X IN (*) DO (
    FOR /F %%G IN (%%~nxX) DO for %%P in (server.sams.log* server.tims.log*) do ECHO %%P
)
ENDLOCAL

So, what I am trying to look for are any files that contain sams or tims in the file name, but ignore any other file in the folder.

And, yes I know I can do the following..

FOR /r "D:\12" %%X IN (server.sams* server.tims*) DO (...

but I have other file names I want to compare..

I have also thought about doing a compare partial strings, but does not seem to work either.. Yes, it seems to work just sams or tims alone and I have tried to use various combinations of GEQ, LSS, etc. to no success. https://superuser.com/questions/541575/comparing-part-of-a-filename-in-a-windows-batch-file

Thanks.

Upvotes: 1

Views: 47

Answers (2)

Leptonator
Leptonator

Reputation: 3519

@rojo - We don't even need the extra %%G "FOR" loop, as this works correctly.

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /r "D:\12" %%X IN (*) DO (
    Set FileName=%%~nxX
    for %%P in (sams tims) do (
        if /i not "!FileName!"=="!FileName:%%P=!" (
                    ECHO %%P "!FileName!"
        )
    )
)
ENDLOCAL

You could of course, replace the %%P with %%G, but you don't need both.. :)

What is helpful with this, is that you can do multiples of these, for example:

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /r "D:\12" %%X IN (*) DO (
    Set FileName=%%~nxX
    for %%P in (sams tims) do (
        if /i not "!FileName!"=="!FileName:%%P=!" (
                    ECHO %%P "!FileName!"
        )
    for %%P in (jims johns) do (
        if /i not "!FileName!"=="!FileName:%%P=!" (
                    ECHO %%P "!FileName!"
        )
    )
)
ENDLOCAL

Thank you for your help in pointing me in the right direction!!

Upvotes: 0

rojo
rojo

Reputation: 24476

If you want to test whether a file contains a substring within a list of possibles, the easiest way is to use findstr with conditional execution.

SETLOCAL
FOR /r "D:\12" %%X IN (*) DO (
    findstr /i "sams tims bobs jims steves" "%%X" >NUL && (
        echo %%X: Match found!
    ) || (
        echo %%X: No match.
    )
)

Or, even simpler, you could eliminate all your for loops entirely and simply use findstr /s /i "sams tims etc" *.

Anyway, your current code is not working because your for %%P loop is only echoing. It isn't actually comparing anything. If you'd prefer to use your nested loops to check for the existence of each substring within the filename, change your code to something like this:

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /r "D:\12" %%X IN (*) DO (
    FOR /F %%G IN (%%~nxX) DO (
        set "line=%%X"
        for %%P in (server.sams.log server.tims.log) do (
            if /i not "!line!"=="!line:%%P=!" (
                ECHO %%P
            )
        )
    )
)
ENDLOCAL

Upvotes: 1

Related Questions