Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 batch string questions

1) Is there any built-in which can tell me if a variable's contents contain only uppercase letters?

2) is there any way to see if a variable contains a string? For example, I'd like to see if the variable %PATH% contains Ruby.

like image 911
Geo Avatar asked Apr 14 '10 04:04

Geo


People also ask

How to add two string in batch file?

String Concatenation is combining two or more strings to create a new string. For instance, let a string “Good” and take another string “Morning” now by string concatenation i.e. “Good” + “Morning” and we got new string i.e. “Good Morning”. This is string concatenation.

What is %% A?

%%a are special variables created by the for command to represent the current loop item or a token of a current line. for is probably about the most complicated and powerful part of batch files. If you need loop, then in most cases for has you covered.

How do I trim a string in a batch file?

Basically, your string will be split into tokens using the underscore as a delimiter (delims=_). Only the second one (tokens=2) will be passed (as variable %%a) to the for loop. The loop will only run once since you are dealing with a single string in this case.

Why am I getting ECHO is off?

If your variable is empty somewhere, it will be the same as having the command "echo" on its own, which will just print the status of echo. That way, if %var2% is empty it will just print "echo var2:" instead of "echo off".


1 Answers

For part 1, findstr is the answer. You can just use the regex feature along with errorlevel:

> set xxokay=ABC
> set xxbad=AB1C
> echo %xxokay%|findstr /r "^[A-Z]*$" >nul:
> echo %errorlevel%
0
> echo %xxbad%|findstr /r "^[A-Z]*$" >nul:
> echo %errorlevel%
1

It's important in this case that you do not have a space between the echo %xxokay% and the pipe character |, since that will result in a space being output which is not one of your acceptable characters.


For part 2, findstr is also the answer (/i is ignore case which may be what you want - leave it off if case must match):

> set xxruby=somewhere;c:\ruby;somewhere_else
> set xxnoruby=somewhere;somewhere_else
> echo %xxruby%|findstr /i ruby >nul:
> echo %errorlevel%
0
> echo %xxnoruby%|findstr /i ruby >nul:
> echo %errorlevel%
1

You can then use:

if %errorlevel%==1 goto :label

to change the behaviour of your script in both cases.

For example, the code segment for the ruby check could be something like:

:ruby_check
    echo %yourvar%|findstr /i ruby >nul:
    if %errorlevel%==1 goto :ruby_check_not_found
:ruby_check_found
    :: ruby was found
    goto :ruby_check_end
:ruby_check_not_found:
    :: ruby was NOT found
:ruby_check_end
like image 196
paxdiablo Avatar answered Sep 27 '22 19:09

paxdiablo