首页 > 解决方案 > 如何使用批处理搜索 .txt 文件中的特定短语

问题描述

我正在尝试创建一个批处理文件,该文件将在 .txt 文件中搜索特定单词并根据找到的单词给我一个响应。但是当我搜索“时间”和“计时器”时,它们都会给出相同的响应,就好像它只找到了“时间”一样。有什么方法可以搜索整个单词或一系列单词,而不仅仅是单词的一部分?

我尝试引用这些单词并双引号引用单词/短语,但它仍然给出相同的响应

这是代码的一部分:

:: Searches for the word "time" and if found, runs the file "Time.bat" in the folder, modules

:Q3
find /I "Time" CurrentConversation.txt
if errorlevel 1 (
    goto :Q4
) else (
    Call Modules/Time.bat

)


:: Searches for the word "timer" and if found, runs the file "Timer.bat" in the folder, modules

:Q4
find /I "Timer" CurrentConversation.txt
if errorlevel 1 (
    goto :Q5
) else (
    call Modules/Timer.bat

)

我希望如果文件“CurrentConversation.txt”有单词计时器,那么它将运行“Timer.bat”。并且如果文件有单词 time 那么它将运行“Time.bat”,但它只运行“Time.bat”,而不管是否存在单词 timer

标签: stringbatch-file

解决方案


有一些更好的方法可以实现这一点,但要坚持使用您当前的代码。您需要意识到字符串Timer也包含Timeso 如果它会time.bat在搜索匹配时启动。所以让我们宁愿使用findstr,我们告诉它搜索Time结尾,这样它在搜索时\>不匹配。TimerTime

:Q3
findstr /I "Time\>" CurrentConversation.
if not errorlevel 0 goto :Q4
Call Modules\Time.bat

:: Searches for the word "timer" and if found, runs the file "Timer.bat" in the folder, modules

:Q4
findstr /I "Timer" CurrentConversation.txt
if not errorlevel 0 goto :Q5
call Modules\Timer.bat

我还做了一些更改以摆脱代码块,这里不需要它。我们只是测试if not errorlevel 0. 一旦它不满足errorlevel它就会落入call bat.bat. 但是,如果它不是其他任何东西errorlevel 0,它将运行 goto。

此外,进行行数学运算的另一种方法是使用双重 findstr 来包含和排除,但这有点矫枉过正。

findstr /I "Time" CurrentConversation.txt | findstr /VI "Timed" test.txt CurrentConversation.txt

请参阅 cmd 的帮助。

  • findstr /?
  • if /?

推荐阅读