A batch program finds a string in a variable

I tried to find solutions in many places, but could not find a specific answer.

I am creating a script package. Below is my code

@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 am trying to find the word "already" in the variable "ras",

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

I tried to use findstr "% ras%" "already" but this also does not work.

+6
source share
3 answers

There are two problems in the code.

The first way findstr works. For each line at its input, it checks whether the line contains (or not) the specified literal or regular expression. The input lines to be tested can be read from a file or from a standard input stream, but not from arguments on the command line. The easiest way to pass a string to findstr

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

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

 if condition ( code ) else ( code ) 

But to check for the presence of a string in a variable, it’s easier to do

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

This will check if the value in the variable is equal to the same value with the replacement of the already string with nothing.

Variable information Change / Replace appearance here .

+6
source

I think I already found a solution ..

  echo %ras% | findstr "already" > nul 

and @Karata I can’t use

  rasdial EVDO cdma cdma | findstr already > NUL 

because I am writing a script for several cases and I want to save the output in a variable. Thank you anyway.

+1
source

"Command syntax is invalid." reported for "else", which does not exist on the command line of the package.

For

 findstr /c:"str" file 

Here str is the literal to search, and the file is the name of the file to perform the search. Therefore, it does not meet your requirements.

I think you need the following.

 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
source

Source: https://habr.com/ru/post/978225/


All Articles