Windows batch if string

Batch file, string variable comparison, if statement

I am trying to compare the logs of a file with a plain string, but it is not getting into if comparison. I am getting » Connect failed» as my 2nd token in echo statement, but not getting any result of IF statement.

1 Answer 1

The first mistake is in line:

This line defines an environment variable with name str1 with a space at end of name with the value » Connect failed» assigned to it. The leading space and the two double quotes are also assigned to the variable as part of the string.

This command line defines an environment variable str1 with the value Connect failed assigned to it.

Run in a command prompt window set /? to get displayed the help for this command on several display pages.

The second mistake is in line:

Options/switches are on Windows specified with / and \ is used as directory separator. So the switch for case-insensitive comparison must be /i and not \i .

Run in a command prompt window if /? for help on IF command.

The third mistake is the attempt to define an environment variable within a command block with assigning a string value to the environment variable and reference the value of this environment variable not using delayed expansion in same command block.

Whenever Windows command interpreter encounters an opening round bracket ( being interpreted as begin of a command block, it parses everything to matching parenthesis ) and replaces all environment variable references done with %VariableName% by current value of the environment variable.

In posted code this means the line

is changed by Windows command interpreter to

before FOR is executed at all because of environment variable str1 is not defined above the FOR command block.

This can be easily seen by changing echo off to echo on or remove the line with echo off or comment it out with command rem and run the batch file from within a command prompt window. Then Windows command interpreter outputs each command block and each command line after preprocessing before execution.

Double clicking on a batch file to execute it is not good as the window is automatically closed on an exit of batch processing because of a syntax error like this one. The usage of pause is no help as this command line is not reached at all on detecting a syntax error by cmd.exe .

A solution would be:

But much easier and also working would be:

For the reason using echo/ instead of echo. to output an empty line see What does an echo followed immediately by a slash do in a Windows CMD file?

Читайте также:  Что делать если пишет что неопознанная сеть windows 10

The usage of I or any other upper case letter instead of n as loop variable is more safe. Why? Run in a command command window for /? and read the output help explaining also %

nI . On usage of %%

n in a batch file it could be unclear for Windows command interpreter if the current value of loop variable n should be used with surrounding double quotes removed or there is a syntax error as the loop variable is missing after modifier

n . Loop variables are case-sensitive. The usage of upper case letters avoids conflicts in interpretation of loop variables with modifiers.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

See Wikipedia article about Windows Environment Variables for a list of predefined environment variables with description like USERPROFILE.

Windows Batch — check if string starts with … in a loop

this grabs the output from a remote branch list with git::

anyhow, I’m finding this frustrating as apparently batch doesn’t have regex

here’s the code I’m using to do this in bash

the grep removes the «origin/HEAD -> origin/master» line of the output of git branch -r

So I’m hoping to ask how to implement the ‘contains’ verb

on a loop variable

this stackoverflow question appears to answer a similar question, although in my attempts to implement as such, I became confused by % symbols and no permutation of them yielded function

EDIT FOR FUTURE READERS: there is some regex with findstr /r piped onto git branch -r

2 Answers 2

should give you a start.

Note: %%r , not %r within a batch file — %r would work directly from the prompt.

Your delims=\ filter will produce that portion up to the first \ of any line from git branch -r which contains HEAD — sorry, I don’t talk bash-ish; you’d need to say precisely what the HEAD string you want to locate is.

Use «delims=» fo the entire line — omitting the delims option will set delimiters to the default set (space, comma, semicolon, etc.)

  • Don’t use ::-comments within a block (parenthesised statement-sequence) as it’s actually a broken label and cmd doesn’t appeciate labels within a block. Use REM comments here instead.

The resultant strings output from the findstr (which acts on a brain-dead verion of regex) will be processed through to the echo (or whatever statement you may substitute here) — if there are none, the for will appear to be skipped.

Quite what your target string would be for findstr I can’t tell. From the prompt, findstr /? may reveal. You may also be able to use find ( find /? ) — but if you are using cygwin the *nix version of find overrides windows-native.

Читайте также:  Linux tap интерфейс как создать

Batch file: Find if substring is in string (not in a file)

In a batch file, I have a string abcdefg . I want to check if bcd is in the string.

Unfortunately it seems all of the solutions I’m finding search a file for a substring, not a string for a substring.

Is there an easy solution for this?

10 Answers 10

Yes, you can use substitutions and check against the original string:

The %str1:bcd=% bit will replace a bcd in str1 with an empty string, making it different from the original.

If the original didn’t contain a bcd string in it, the modified version will be identical.

Testing with the following script will show it in action:

And the results of various runs:

A couple of notes:

  • The if statement is the meat of this solution, everything else is support stuff.
  • The x before the two sides of the equality is to ensure that the string bcd works okay. It also protects against certain «improper» starting characters.

You can pipe the source string to findstr and check the value of ERRORLEVEL to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:

When this is run in CMD.EXE, we get:

I usually do something like this:

I don’t know if this is the best way.

For compatibility and ease of use it’s often better to use FIND to do this.

You must also consider if you would like to match case sensitively or case insensitively.

The method with 78 points (I believe I was referring to paxdiablo’s post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.

( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )

In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.

For these reasons this is a preferable alternative methodology:

Use: Find [/I] [/V] «Characters to Match»

[/I] (case Insensitive) [/V] (Must NOT contain the characters)

As mentioned this is great for things which are not in variables which allow string substitution as well:

Check a string for a substring in a batch file (Windows)?

Let’s say I have some text in a variable called $1. Now I want to check if that $1 contains a certain string. If it contains a certain string I want to print a message. The printing is not the problem, the problem is the check. Any ideas how to do that?

3 Answers 3

The easiest way in my opinion is this :

Basiclly the string after ‘:’ is the string you are looking for and you are using not infront of the if because %string:*% will remove the * from the string making them not equal.

Читайте также:  Снимок экрана mac os сочетание клавиш

The SET search and replace trick works in many cases, but it does not support case sensitive or regular expression searches.

If you need a case sensitive search or limited regular expression support, you can use FINDSTR.

To avoid complications of escaping special characters, it is best if the search string is in a variable and both search and target are accessed via delayed expansion.

You can pipe $1 into the FINDSTR command with the ECHO command. Use ECHO( in case $1 is undefined, and be careful not to add extra spaces. ECHO !$1! will echo ECHO is off. (or on) if $1 is undefined, whereas ECHO(!$1! will echo a blank line if undefined.

FINDSTR will echo $1 if it finds the search string — you don’t want that so you redirect output to nul. FINDSTR sets ERRORLEVEL to 0 if the search string is found, and 1 if it is not found. That is what is used to check if the string was found. The && and || is a convenient syntax to use to test for match (ERRORLEVEL 0) or no match (ERRORLEVEL not 0)

The regular expression support is rudimentary, but still useful.

See FINDSTR /? for more info.

This regular expression example will search $1 for «BEGIN» at start of string, «MID» anywhere in middle, and «END» at end. The search is case sensitive by default.

How to see if a string contains a substring using batch

Currently trying to see if a string, in this case the current line of a text file, contains a substring # . I am new to batch, so I am not sure exactly how I would do something like this. Here is the code set substring = #

4 Answers 4

Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named «FLAG Space » to a value of » Space N»

The syntax SET «var=value» (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used «quoteless».

As an alternative to find , you can use string substitution, like this:

This approach uses delayed environment variable expansion. Type setlocal /? in command prompt to find out how to enable it, and set /? to see how it works (read variables like !string! instead of %string% ) and what it means. set /? also describes the string substitution syntax.

I had to create a function:

Remember it is not case sensitive by default. Add the word true to the end of the Call if you would like to be case sensitive such as:

And these Functions to the bottom of your Batch File.

And remember you MUST add «SETLOCAL ENABLEDELAYEDEXPANSION» to the top of your batch file or else none of this will work properly.

Оцените статью