Anuj Mittal
Anuj Mittal

Reputation: 73

How to use Find statement with 'If/else statement' using CMD

I am trying to use find command with if..else statement. What I actually want to do is, search for a specific string in multiple log files. If I find that string I want to append the name of that file with "Passed" else "Failed" into another text file.

I have tried the following but it doesn't work:

if (find /n /i "0 error" "filename.log") (
    echo "Passed" > log.txt
) else (
    echo "Failed" > log.txt
)

Upvotes: 1

Views: 8440

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

CMD/batch doesn't support commands in if statements. You need to evaluate the errorlevel (the exit code of the command) after running the command:

set "logfile=filename.log"
find /n /i "0 error" "%logfile%" >nul
if %errorlevel% equ 0 (
    >>log.txt echo %logfile% - Passed
) else (
    >>log.txt echo %logfile% - Failed
)

Upvotes: 2

Compo
Compo

Reputation: 38623

If I understand your question correctly:

To get a .txt file containing only the names of the logs in the current directory which contained 0 error:

FindStr /MIC:"0 Error" *.log>"Passed.txt"

If you wanted a log.txt to prodvide feedback on each log file in the current directory, instead…

From the Command Prompt:

(For %A In (*.log) Do @FindStr /MIC:"0 Error" "%A">Nul&&(@Echo %A Passed)||@Echo %A Failed)>"log.txt"

From a batch file:

@Echo Off
(For %%A In (*.log) Do FindStr /MIC:"0 Error" "%%A">Nul&&(
    Echo %%A Passed)||Echo %%A Failed)>"log.txt"

Upvotes: 1

Related Questions