如何查找具有特定字符串的变量?

问题描述 投票:0回答:3

我想创建一个脚本来检查所有以'var'开头的变量是否为某个字符串。我在下面的代码中有三个变量,我希望它找到字符串code并输出包含它的变量的名称。

set var1=hi
set var2=code
set var3=bye

:: variable checker here

echo Variable %variable% has the string 'code' in it.

在上面的示例中,输出应为var2,但是我丝毫不知道如何检查字符串变量。

batch-file
3个回答
0
投票

这是我的评论,以Rem arks完整显示它是如何工作的:

@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'.

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

0
投票

您可以使用findstr查找具有特定值的变量:

findstr

要处理结果,请使用2> nul set VAR | findstr /X /I /C:"[^=][^=]*=code"

for /F loop

如果要进行区分大小写的比较,请删除for /F

如果值以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. -符号开头,则它将/它们在输出中丢失。

© www.soinside.com 2019 - 2024. All rights reserved.