Celeb Glow
updates | March 12, 2026

Filter files whose names contain a keyword in CMD

In working on a script that computes, and outputs to a file, the total cyclomatic complexities of a project under test, I am trying to filter out files whose names (including path) contains "test". (Such files only exist for testing purposes, and are therefore exempt from computation.)

So far, I have the following code:

rem write temporary file, to append command line output to
SETLOCAL
SET tmpfile=tmp_ComplexityAnalysis.txt
echo. 2>%tmpfile%
rem perform cyclomatic complexity analysis on all the files, iff those files are not test files and have some functions in them
echo %tmpfile%
for /R apiserver_sdk %%G in (*.go) DO ( rem filter out "test" files gocyclo %%G >> %tmpfile%
)

I don't know how to exclude "test" or where.

UPDATE: Changing the body of the for loop to :

DIR /A %%G| findstr test
IF %ERRORLEVEL% NEQ 0 ( rem filter out "test" files gocyclo %%G >> %tmpfile%
)

doesn't work because, somehow, %ERRORLEVEL% is always zero.

2

2 Answers

As the questioner has found, %ErrorLevel% is not being set. I don't know whether delayed expansion and !ErrorLevel! would work, but what I found was that findstr is setting its return value, so either of the following scripts works:-

for /R apiserver_sdk %%G in (*.go) DO ( rem filter out "test" files echo %%G | findstr /i test if errorlevel 1 ( gocyclo %%G >> %tmpfile% )
)

or:-

for /R apiserver_sdk %%G in (*.go) DO ( rem filter out "test" files echo %%G | findstr /i test || ( gocyclo %%G >> %tmpfile% )
)

If the gocyclo command is the only one needed, the command group surrounding it could be removed.

1
DIR /B | FOR /F %x IN ('FIND "test"') DO ( ECHO Execute something using "%x"
)

Backwards, to exclude files which contains "test" substring in a name - add /V key to the FIND command.

screenshot

this needs to happen for all the .go files in the directory that don't have "test" in their pathnames

DIR /B *.go | FOR /F %x IN ('FIND /V "test"') DO( ECHO Execute something using "%x"
)
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy