批处理程序查找变量中的字符串

11

我在许多地方寻找解决方案,但找不到具体的答案。

我正在创建一个批处理脚本。 以下是我的代码:

    @echo off
    SETLOCAL EnableDelayedExpansion
    cls
    for /f "delims=" %%a in ('rasdial EVDO cdma cdma') do set "ras=!ras! %%a"

    findstr /C:"%ras%" "already"

    if %errorlevel% == 0 
    (
        echo "it says he found the word already"
    )
    else
    (
        echo "it says he couldn't find the word already"
    )

输出:

    FINDSTR: Cannot open already
    The syntax of the command is incorrect.

我正在尝试在变量 'ras' 中查找单词“already”,

问题似乎出现在 findstr /C:"%ras%" "already"

我尝试使用 findstr "%ras%" "already" 但这也不起作用。

3个回答

11

你的代码存在两个问题。

第一个问题在于findstr的工作方式。对于其输入的每一行,它会检查该行是否包含(或不包含)所指定的文字或正则表达式。将要测试的输入行可以从文件或标准输入流中读取,但不能从命令行参数中读取。最简单的方式是将该行导入到findstr命令中。

echo %ras% | findstr /c:"already" >nul

第二个问题是if命令的书写方式。开括号必须与条件在同一行,else子句必须与第一个闭括号在同一行,并且else子句中的开括号必须与else子句在同一行(参见这里)。

if condition (
    code
) else (
    code 
)

但是要测试变量中是否存在该字符串,更容易的做法是:

if "%ras%"=="%ras:already=%" (
    echo already not found
) else (
    echo already found
)

这将测试变量中的值是否等于用字符串already替换为空后的相同值。

有关变量编辑/替换的信息,请参见此处


1
非常聪明的替换字符串技巧!我看过很多使用大量“查找”和类似方法的示例,但这种方法非常快速、干净,而且易于理解! - Gruber

3

好像我已经找到了解决方案...

    echo %ras% | findstr "already" > nul

而且@Karata,我不能使用

    rasdial EVDO cdma cdma | findstr already > NUL

因为我正在编写多种情况的脚本,我希望将输出存储在一个变量中。无论如何,谢谢。

0
“命令语法不正确”是针对“else”的报告,而在批处理命令行中不存在该命令。
关于:
findstr /c:"str" file

这里的 str 是要搜索的文字,file 是要执行搜索的文件名。所以这不符合您的要求。

我认为以下是您需要的。

rasdial EVDO cdma cdma | findstr already > NUL

if %errorlevel% EQU 0 (
    echo "it says he found the word already"
)

if %errorlevel% NEQ 0 (
    echo "it says he couldn't find the word already"
)

“else”确实存在(作为“if”语法的一部分)。原帖作者只是弄错了语法。 - Stephan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接