【问题标题】:How to find if a file contains a given string using Windows command line如何使用 Windows 命令行查找文件是否包含给定字符串
【发布时间】:2011-04-11 20:04:22
【问题描述】:

我正在尝试为 Windows XP 创建一个批处理 (.bat) 文件来执行以下操作:

If (file.txt contains the string 'searchString') then (ECHO found it!) 
ELSE(ECHO not found)

到目前为止,我已经找到了一种使用 FIND 命令在文件中搜索字符串的方法,该命令返回文件中找到字符串的行,但无法进行条件检查就可以了。

例如,这不起作用。

IF FIND "searchString" file.txt ECHO found it!

这也不是:

IF FIND "searchString" file.txt=='' ECHO not found

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: windows batch-file cmd


    【解决方案1】:

    来自其他帖子:

        find /c "string" file >NUL
        if %errorlevel% equ 1 goto notfound
            echo found
        goto done
        :notfound
            echo notfound
        goto done
        :done
    

    当您需要不区分大小写的检查时,请使用 /i 开关:

        find /i /c "string" file >NUL
    

    或者类似:如果没有找到写入文件。

        find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )
    

    或类似:如果找到写入文件。

        find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )
    

    或者类似的东西:

        find /c "%%P" file.txt  && ( echo found ) || ( echo not found )
    

    【讨论】:

    • 考虑添加 /i 开关以获得不区分大小写的比较。大多数时候,这就是所需要的;-)
    【解决方案2】:

    我使用 DOS 命令行来执行此操作。 实际上是两条线。第一个使“当前目录”成为文件所在的文件夹 - 或文件所在的一组文件夹的根文件夹。第二行进行搜索。

    CD C:\TheFolder
    C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
    

    您可以在this link找到有关参数的详细信息。

    希望对你有帮助!

    【讨论】:

    • 注意:在脚本中使用 CD 时,添加 /D 标志以允许驱动器切换以及文件夹更改,因为大多数情况下,这是预期的行为。
    猜你喜欢
    • 2012-10-31
    • 1970-01-01
    • 2011-10-06
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多