Batch program find string in variable

43.9k Views Asked by At

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.

3

There are 3 best solutions below

1
On

"The syntax of the command is incorrect." is reported for 'else', which does not exist in batch command line.

For

findstr /c:"str" file

Here str is the literal to be searched, and file is the file name to perform search. So this does not meet your requirement.

I think the following is what you need.

rasdial EVDO cdma cdma | findstr already > NUL

if %errorlevel% EQU 0 (
    echo "it says he found the word already"
)

if %errorlevel% NEQ 0 (
    echo "it says he couldn't find the word already"
)
0
On

Seems I already found the solution..

    echo %ras% | findstr "already" > nul

and @Karata I can't use

    rasdial EVDO cdma cdma | findstr already > NUL

because I am writing script for multiple cases and I want to store output in a variable..Thanks anyways.

1
On

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.