2014-11-15 63 views
6

我試圖在很多地方找到解決方案,但找不到具體答案。批處理程序在變量中查找字符串

我正在創建批處理腳本。 以下是到目前爲止我的代碼

@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" 
    ) 

OUTPUT:

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

我試圖查找單詞 '已經' 變量 'ras基因',

的問題似乎是在 FINDSTR/C: 「%RAS%」 「已經」

我試着用 findstr「%ras%」「已經」 但這不起作用。

回答

0

「該命令的語法不正確。」報告爲'else',這在批處理命令行中不存在。

對於

findstr /c:"str" file 

這裏str是要搜索的文本,文件是執行搜索的文件名。所以這不符合你的要求。

我認爲以下是你需要的。

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" 
) 
1

看來我已經找到了解決辦法..

echo %ras% | findstr "already" > nul 

和@Karata因爲我寫了多個案例腳本我不能使用

rasdial EVDO cdma cdma | findstr already > NUL 

,我想存儲輸出在一個變量..謝謝反正。

6

你的代碼有兩個問題。

第一個是findstr如何工作。對於其輸入中的每一行,它會檢查該行是否包含指示的文字或正則表達式。要測試的輸入行可以來自文件或標準輸入流,但不能來自命令行中的參數。它最簡單的方法來管行成findstr命令

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

的第二個問題是if命令是怎麼寫的。左括號必須在同一行,該狀態下,else子句必須在同一行,第一右括號和else子句中的左括號必須在同一行的是,else條款(見here

if condition (
    code 
) else (
    code 
) 

但以測試變量中的字符串的存在,這是容易做到

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

這將測試是否在變量中的值等於與相同的值字符串already被替換爲無。

有關的信息變量編輯/替換看起來here

+0

非常聰明替換字符串絕招!我已經看到了很多與噸find'和類似的例子',但這是非常快,乾淨,易於理解! – Gruber

相關問題