【问题标题】:search for if a specific text (group of string) is present into a file using a batch file使用批处理文件搜索文件中是否存在特定文本(字符串组)
【发布时间】:2013-04-07 12:03:25
【问题描述】:

我正在使用批处理文件搜索文件中是否存在特定文本(字符串组)。 这是我写的,但它不适用于文本。它只适用于字符串(不搜索文本)。

rem %1 is name of the file whose text is being found
FindStr /C:%2 %1 
If %ERRORLEVEL% EQU 0 echo text %2 is Present
If %ERRORLEVEL% EQU 1 echo text %2 is not Present

例如,如果必须将文本“我吃早餐”搜索到包含“我每天吃早餐”的文件中,则命令 echo 必须打印这个: “文本我吃早餐了”。

任何帮助!请。

【问题讨论】:

    标签: search text batch-file


    【解决方案1】:

    此文件完美运行。

    你需要找到你的文本的命令行是

    yourbatch yourtextfile.txt "I have breakfast"
    

    如果你执行

    yourbatch yourtextfile.txt I have breakfast
    

    然后它会简单地搜索I,因为SPACE是一个分隔符,为了搜索一个空格分隔的字符串,你需要"quote字符串"

    同样,如果您的文件名包含空格,则与文件名相同。

    yourbatch "your text file.txt" "I have breakfast"
    
    
    %%1 is "your text file.txt" 
    %%2 is "I have breakfast"
    

    包括引号。

    要删除引号,如果您愿意,可以使用 %~2

    所以 - 你可以ECHO

    ECHO with quotes:%2 and without: %~2
    

    另外:小心

    If %ERRORLEVEL% EQU 0 echo text %2 is Present
    If %ERRORLEVEL% EQU 1 echo text %2 is not Present
    

    ECHO 是少数几个不会更改errorlevel 的命令之一。许多人会改变它,例如,如果你要写

    如果 %ERRORLEVEL% EQU 0 echo Y|find "x" >nul 如果 %ERRORLEVEL% EQU 1 回显文本 %2 不存在

    那么如果找到echo Y|find "x" >nul是因为上一步中的errorlevel是0,那么因为echo Y|find "x" >nul将errorlevel设置为1,第二行也会被执行。

    【讨论】:

    • 太棒了!也感谢您提供详细信息。
    【解决方案2】:

    这应该可以工作,如果你调用脚本script.bat "file name" "search string":

    @echo off&setlocal
    rem %1 is name of the file whose text is being found
    FindStr /C:"%~2" "%~1" >nul
    If %ERRORLEVEL% EQU 0 echo text %2 is Present
    If %ERRORLEVEL% EQU 1 echo text %2 is not Present
    

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

      FindStr /C:"%~2" "%~1" >nul && echo text "I have breakfast is present".
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        • 2012-05-25
        • 1970-01-01
        • 1970-01-01
        • 2015-08-15
        • 2011-10-23
        相关资源
        最近更新 更多