Search code examples
batch-filefindstr

batch file findstr, how to?


I'm writing a batch file:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('DIR %BASE_FLDR% /S /B /A:D') DO (
    ECHO [%%F] | FINDSTR /E /X /IC:"%BLD_TYPE%" [%%F] >NUL && (
        ECHO %%F
    )
)

What I want to do is be able to call the batch file like so:

copydlls ./ Release

I want the batch file to use command line argument 1 (%1) to specify the starting location, %2 would be either "Debug" or "Release", this parsing of the arguments is fine.

In the loop I am trying to use FINDSTR to find all sub-folders that end with the folder name supplied in %2.

This bit isn't correct and is where I need help.

So far my code will capture folders correctly event where a folder contains spaces the [] fixes that, but now it doesn't match the end of string.


Solution

  • Instead of using if %errorlevel% try if !errorlevel!, because percent expansion is evaluated when a block is parsed, before it is executed.

    But that wouldn't help, as your code is broken. Findstr /X can't never match, because /X full line must match can't be true for BLD_TYPE only.

    Btw. it could be simplyfied by moving the findstr into the FOR loop.

    FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /E /IC:"%BLD_TYPE%" "') DO (
       echo #1 %%F
    )