windows 批处理文件:查找子字符串是否在字符串中(不在文件中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7005951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Batch file: Find if substring is in string (not in a file)
提问by Ben
In a batch file, I have a string abcdefg
. I want to check if bcd
is in the string.
在批处理文件中,我有一个 string abcdefg
。我想检查是否bcd
在字符串中。
Unfortunately it seems all of the solutions I'm finding search a filefor a substring, not a string for a substring.
不幸的是,我找到的所有解决方案似乎都在搜索文件中的子字符串,而不是子字符串的字符串。
Is there an easy solution for this?
有没有一个简单的解决方案?
回答by paxdiablo
Yes, you can use substitutions and check against the original string:
是的,您可以使用替换并检查原始字符串:
if not x%str1:bcd=%==x%str1% echo It contains bcd
The %str1:bcd=%
bit will replace a bcd
in str1
with an empty string, making it different from the original.
该%str1:bcd=%
位将用空字符串替换bcd
in str1
,使其与原始字符串不同。
If the original didn't contain a bcd
string in it, the modified version will be identical.
如果原始版本中不包含bcd
字符串,则修改后的版本将是相同的。
Testing with the following script will show it in action:
使用以下脚本进行测试将显示它的实际效果:
@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal
And the results of various runs:
以及各种运行的结果:
c:\testarea> testprog hello
c:\testarea> testprog abcdef
It contains bcd
c:\testarea> testprog bcd
It contains bcd
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 stringbcd
works okay. It also protects against certain "improper" starting characters.
- 该
if
声明是该解决方案的肉,其他的都是支持的东西。 x
等式两边的before 是为了确保字符串bcd
正常工作。它还可以防止某些“不正确”的起始字符。
回答by ghostdog74
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:
您可以通过管道将源字符串发送到findstr
并检查 的值ERRORLEVEL
以查看是否找到了模式字符串。零值表示成功并且找到了模式。下面是一个例子:
::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off
echo.%2 | findstr /C:"%1" 1>nul
if errorlevel 1 (
echo. got one - pattern not found
) ELSE (
echo. got zero - found pattern
)
When this is run in CMD.EXE, we get:
当它在 CMD.EXE 中运行时,我们得到:
C:\DemoDev>y pqrs "abc def pqr 123"
got one - pattern not found
C:\DemoDev>y pqr "abc def pqr 123"
got zero - found pattern
回答by user839791
I usually do something like this:
我通常做这样的事情:
Echo.%1 | findstr /C:"%2">nul && (
REM TRUE
) || (
REM FALSE
)
Example:
例子:
Echo.Hello world | findstr /C:"world">nul && (
Echo.TRUE
) || (
Echo.FALSE
)
Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)
Output:
输出:
TRUE
FALSE
I don't know if this is the best way.
我不知道这是不是最好的方法。
回答by Ben Personick
For compatibility and ease of use it's often better to use FIND to do this.
为了兼容性和易用性,通常最好使用 FIND 来执行此操作。
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.
具有 78 分的方法(我相信我指的是 paxdiablo 的帖子)只会匹配区分大小写,因此您必须为您可能想要匹配的每个可能的迭代对每个案例变体进行单独检查。
( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )
(真是太痛苦了!只有 3 个字母,这意味着要进行 9 种不同的测试才能完成检查!)
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.
此外,很多时候最好匹配命令输出、循环中的变量或批处理/CMD 中的指针变量的值,这并不直接。
For these reasons this is a preferable alternative methodology:
由于这些原因,这是一种更可取的替代方法:
Use: Find [/I] [/V] "Characters to Match"
使用:查找[/I] [/V]“要匹配的字符”
[/I] (case Insensitive) [/V] (Must NOT contain the characters)
[/I](不区分大小写)[/V](不能包含字符)
As Single Line:
作为单行:
ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
Multi-line:
多线:
ECHO.%Variable%| FIND /I "ABC">Nul && (
Echo.Found "ABC"
) || (
Echo.Did not find "ABC"
)
As mentioned this is great for things which are not in variables which allow string substitution as well:
如前所述,这对于不在允许字符串替换的变量中的事物非常有用:
FOR %A IN (
"Some long string with Spaces does not contain the expected string"
oihu AljB
lojkAbCk
Something_Else
"Going to evaluate this entire string for ABC as well!"
) DO (
ECHO.%~A| FIND /I "ABC">Nul && (
Echo.Found "ABC" in "%A"
) || ( Echo.Did not find "ABC" )
)
Output From a command:
NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
As you can see this is the superior way to handle the check for multiple reasons.
回答by byorking
If you are detecting for presence, here's the easiest solution:
如果您正在检测是否存在,这是最简单的解决方案:
SET STRING=F00BAH
SET SUBSTRING=F00
ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE TRUE) else (ECHO CASE FALSE)
This works great for dropping the output of windows commands into a boolean variable. Just replace the echo with the command you want to run. You can also string Findstr's together to further qualify a statement using pipes. E.G. for Service Control (SC.exe)
这对于将 Windows 命令的输出放入布尔变量非常有用。只需将 echo 替换为您要运行的命令即可。您还可以将 Findstr 串在一起以使用管道进一步限定语句。用于服务控制的 EG (SC.exe)
SC QUERY WUAUSERV | findstr /C:"STATE" | FINDSTR /C:"RUNNING" & IF ERRORLEVEL 1 (ECHO case True) else (ECHO CASE FALSE)
That one evaluates the output of SC Query for windows update services which comes out as a multiline text, finds the line containing "state" then finds if the word "running" occurs on that line, and sets the errorlevel accordingly.
那一个评估 SC Query for windows update services 的输出,该输出作为多行文本出现,找到包含“state”的行,然后查找该行是否出现“running”一词,并相应地设置错误级别。
回答by Andy Sug
I'm probably coming a bit too late with this answer, but the accepted answer only works for checking whether a "hard-coded string" is a part of the search string.
我对这个答案可能来得太晚了,但接受的答案仅适用于检查“硬编码字符串”是否是搜索字符串的一部分。
For dynamic search, you would have to do this:
对于动态搜索,您必须这样做:
SET searchString=abcd1234
SET key=cd123
CALL SET keyRemoved=%%searchString:%key%=%%
IF NOT "x%keyRemoved%"=="x%searchString%" (
ECHO Contains.
)
Note: You can take the two variables as arguments.
注意:您可以将这两个变量作为参数。
回答by Riccardo La Marca
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)
回答by T.Todua
回答by Zimba
The solutions that search a filefor a substring can also search a string, eg. find
or findstr
.
In your case, the easy solutionwould be to pipe a string into the command instead of supplying a filename eg.
搜索文件以获取子字符串的解决方案也可以搜索字符串,例如。find
或findstr
。
在您的情况下,简单的解决方案是将字符串通过管道传输到命令中,而不是提供文件名,例如。
case-sensitive string:echo "abcdefg" | find "bcd"
区分大小写的字符串:echo "abcdefg" | find "bcd"
ignore case of string:echo "abcdefg" | find /I "bcd"
忽略字符串的大小写:echo "abcdefg" | find /I "bcd"
IF no match found, you will get a blank line response on CMD and %ERRORLEVEL% set to 1
如果未找到匹配项,您将在 CMD 上得到一个空行响应,并将 %ERRORLEVEL% 设置为 1