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.
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
this is not a batch solution (cmd.exe), but an easier alternative using vbscript, which by default is already installed on your system.
Set objArgs = WScript.Arguments
var=objArgs(0)
check=var
If check=UCase(var) Then
WScript.Echo "String contains all uppercase"
Else
WScript.Echo "String doesn't contain all uppercase"
End If
' to check string contains substring
mystring="This is my ruby string"
check="ruby"
If InStr(mystring,check)>0 Then
WScript.Echo "string contains ruby"
End If
save the file as myscript.vbs
and run it like this
C:\test>cscript //nologo myscript.vbs abC
String doesn't contain all uppercase
string contains ruby
C:\test>cscript //nologo myscript.vbs ABCD
String contains all uppercase
string contains ruby
using batch(cmd.exe) for string manipulation is the last thing you would want to do, unless you are absolutely restricted. Otherwise, use the more appropriate tool for the job.
精彩评论