我想创建一个脚本,该脚本检查所有以'var'开头的变量是否为某个字符串。我在下面的代码中有三个变量,我希望它找到字符串code
并输出包含它的变量的名称。
set var1=hi
set var2=code
set var3=bye
:: variable checker here
echo Variable %variable% has the string 'code' in it.
在上面的示例中,输出应为var2
,但我丝毫不知道如何检查字符串变量。
答案 0 :(得分:0)
以下是我的评论,以Rem
方格结尾以说明其工作原理:
@Echo Off
Rem Undefine any variables whose names begin with Var
For /F "Delims==" %%A In ('Set Var 2^>NUL')Do Set "%%A="
Rem Define some new variables whose names begin with Var
Set "Var1=Some string"
Set "Var2=A code string"
Set "Var3=Another string with code in it"
Set "Var4=345678"
Rem Show all variables whose names begin with Var and their values
Set Var 2>NUL
Rem Check for any variable whose names begin with Var and has a value with the string 'code' in it
For /F "Delims==" %%A In ('Set Var 2^>NUL^|Find "code"')Do Echo Variable %%A has the string 'code' in it.
Rem Pause the script to see the output
Pause
在搜索所需的字符串时,您当然可以将/I
和Find
选项一起使用来忽略大小写。
如果要查看大小写是否不敏感地匹配code
,可以将第二个For
循环更改为:
For /F "Tokens=1*Delims==" %%A In ('Set Var 2^>NUL')Do If /I "%%B"=="code" Echo Variable %%A has the string value 'code'.
答案 1 :(得分:0)
假设变量应包含任何形式的code
,这确实很简单
@echo off
for /f "tokens=1,* delims==" %%i in ('set ^|findstr "code" ^|findstr "var"') do echo %%i has code in it as %%j
或者如果大小写不重要:
@echo off
for /f "tokens=1,* delims==" %%i in ('set ^|findstr /i "code" ^|findstr /i "var"') do echo %%i has code in it as %%j
答案 2 :(得分:0)
您可以使用findstr
查找具有特定值的变量:
2> nul set VAR | findstr /X /I /C:"[^=][^=]*=code"
要处理结果,请使用for /F
loop:
for /F "tokens=1* delims== eol==" %%V in ('
2^> nul set VAR ^| findstr /X /I /C:"[^=][^=]*=code"
') do echo Variable %%V is set to %%W.
如果要进行区分大小写的比较,请删除/I
。
如果您不希望整个值都匹配,请将/X
替换为/B
以匹配开头,或者替换为/E
以匹配结尾,或者将/X
删除为在任何地方匹配。
如果值以=
-符号开头,则它将在输出中丢失。