string 如何使用批处理查看字符串是否包含子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34077831/
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
How to see if a string contains a substring using batch
提问by FyreeW
Currently trying to see if a string, in this case the current line of a text file, contains a substring #
. I am new to batch, so I am not sure exactly how I would do something like this. Here is the code
set substring = #
当前正在尝试查看字符串(在本例中为文本文件的当前行)是否包含子字符串#
。我是批处理的新手,所以我不确定我将如何做这样的事情。这是代码
set substring = #
for /f "delims=," %%a in (Text.txt) do (
set string = %%a
//check substring method
echo %string%
)
回答by Magoo
echo %%a|find "substring" >nul
if errorlevel 1 (echo notfound) else (echo found)
Batch is sensitive to spaces in a SET
statement. SET FLAG = N
sets a variable named "FLAGSpace" to a value of "SpaceN"
批处理对SET
语句中的空格敏感。SET FLAG = N
将名为“FLAG Space”的变量设置为“ SpaceN”的值
The syntax SET "var=value"
(where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a
can safely be used "quoteless".
语法SET "var=value"
(其中 value 可能为空)用于确保分配的值中不包含任何杂散的尾随空格。set /a
可以安全地使用“无引号”。
回答by aschipfl
As an alternative to find
, you can use string substitution, like this:
作为替代find
,您可以使用字符串替换,如下所示:
@echo off
setlocal EnableDelayedExpansion
set "substring=#"
for /f "delims=," %%a in (Text.txt) do (
set "string=%%a"
if "!string:%substring%=!"=="!string!" (
rem string with substring removed equals the original string,
rem so it does not contain substring; therefore, output it:
echo(!string!
)
)
endlocal
This approach uses delayed environment variable expansion. Type setlocal /?
in command prompt to find out how to enable it, and set /?
to see how it works (read variables like !string!
instead of %string%
) and what it means. set /?
also describes the string substitution syntax.
这种方法使用延迟环境变量扩展。键入setlocal /?
命令提示符以了解如何启用它,并set /?
查看它是如何工作的(读取变量,!string!
而不是%string%
)及其含义。set /?
还描述了字符串替换语法。