windowsbatch-filefindstr

How to check for a certain pattern in Windows batch


I want to run something like this

C:\> mybatch.bat somefile.gz

or like this

C:\> mybatch.bat somefile.mps.gz

Inside the batch I want to check wether the argument ended with .gz or with .mps.gz.

This doesn't work

if findstr ".mps.gz" %1 (
    echo ".mps.gz file"
) else (
    echo ".gz file"
)

What is the right way to do this?

EDIT 1 (from https://stackoverflow.com/users/2128947/magoo):

set ZIP="C:\Program Files\7-Zip\7zFM.exe"

echo %1|findstr /i /L /e /C:".mps.gz">nul&if errorlevel 1 ( 
    echo ".gz only %1"
    %ZIP% %1
) else (
    echo ".mps.gz %1"
    call freempsgz2lpt.bat %1
)

pause -1

doesn't recognize the .mps.gz extension if I associate the batch file with extension .gz and double click in Windows Explorer. From commandline it works well.

EDIT 2: I changed the proposal to

echo %1|findstr /i /L /e /C:".mps.gz""">nul&if errorlevel 1 ( ...

Now it works with file association in Windows Explorer but not on commandline. This is ok for me.


Solution

  •  echo %~1|findstr /i /L /e /C:".mps.gz">nul&if errorlevel 1 (echo does not end .mps.gz) else (echo ends mps.gz)
    

    findstr is a utility that sets errorlevel = 1 if the string is not matched and 0 if matched.

    Documentation : findstr /? from the prompt or This tome or many examples.

    In brief, /I means case-insensitive, /L is literal-match (as distinct from default /R - partial-regex) /E match at end of line, /C:"stringtomatch"