Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch how to set FINDSTR result to a variable and disable findstr print to console

Tags:

batch-file

My batch program

FINDSTR  /C:"Result Comparison failure"  %tmp_result_file% 

I want to do the folloiwng , set the result of the above command to a variable. If found, set the first line to varible or set the all found line to a varible is OK for me.

also the above commmand will print the findstr command to console even @echo off. is there any method to disable the print.

thanks a lot


part of my script, what i do is run command on every line in sourcefile and put the run result into a tmp file, then use find str to find the failed string to check the run result.

for /f  %%a in (%source_file%) do (
    echo  run %%a >> %output_file%
    call  %run_script_command% %%a > %tmp_result_file% 2>&1
    ::notepad %tmp_result_file%
      for /f %%i in ('FINDSTR /C:"Result Comparison failure"  %tmp_result_file%') do  echo %%ixxx
    echo xx
)

very strange , the result is:

    xx
    Resultxxx
    xx

the background is that i have two items in %source_file%, so the out for run 2 times.
for the first one, the FINDSTR can not find anything, so print xxx
for the second one, it find one in findstr , but only print "Result" instead of "Result Comparison failure", also the xx is print before it in result. Very Strange!

like image 712
Ben Xu Avatar asked Sep 30 '11 02:09

Ben Xu


1 Answers

The first problem is because you just take the first token from FOR. To solve it, you have two solutions, either to echo the complete line where the string is found...

for /f "tokens=*" %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do echo %%i

or echo the three tokens found

for /f %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do echo %%i %%j %%k

the second problem, the xx echoed two times is because you run two times the command. The first xx is the one from the first run, the second one is from the second run. If you want to prevent the second one, you need to use some additional logic. For example, setting a variable and then checking it. Warning, setting a variable in a loop requires enabling delayed expansion and using the !xx! syntax (see HELP SET for a detailed explanation)

setlocal enabledelayedexpansion
...
set result=
for /f "tokens=*" %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do (
  set result=%%i
)
if "!result!"=="" ( 
  echo !result!
) else (
  echo xx
)
like image 117
PA. Avatar answered Oct 27 '22 19:10

PA.