Batch program find string in variable

Sid1024 picture Sid1024 · Nov 15, 2014 · Viewed 31.1k times · Source

I tried to find the solutions in many places but couldn't find specific answer.

I am creating a batch script. The following is my code so far

    @echo off
    SETLOCAL EnableDelayedExpansion
    cls
    for /f "delims=" %%a in ('rasdial EVDO cdma cdma') do set "ras=!ras! %%a"

    findstr /C:"%ras%" "already"

    if %errorlevel% == 0 
    (
        echo "it says he found the word already"
    )
    else
    (
        echo "it says he couldn't find the word already"
    )

OUTPUT :

    FINDSTR: Cannot open already
    The syntax of the command is incorrect.

I'm trying to find the word 'already' in variable 'ras',

The problem seems to be in findstr /C:"%ras%" "already"

I tried using findstr "%ras%" "already" but that doesn't work too.

Answer

MC ND picture MC ND · Nov 15, 2014

There are two problems in your code.

The first one is how findstr works. For each line in its input, it checks if the line contains (or not) the indicated literal or regular expression. The input lines that will be tested can be readed from a file or from the standard input stream, but not from the arguments in the command line. The easiest way it to pipe the line into the findstr command

echo %ras% | findstr /c:"already" >nul

The second problem is how the if command is written. The opening parenthesis must be in the same line that the condition, the else clause must be in the same line that the first closing parenthesis, and the opening parenthesis in the else clause must be in the same line that the else clause (see here)

if condition (
    code
) else (
    code 
)

But to test for presence of the string in the variable, it is easier to do

if "%ras%"=="%ras:already=%" (
    echo already not found
) else (
    echo already found
)

This will test if the value in the variable is equal to the to the same value with the string already replaced by nothing.

For info on Variable Edit/Replace look here.