使用批处理脚本在不断变化的文件中查找字符串

Looking for a string on a constantly changing file with a batch script

我有一个不断添加新行的 .log 文件,我想要一个批处理脚本来检测新行何时具有特定字符串。

首先,我复制 .log 文件并将其更改为 .txt 然后我读了最后一行

下面是 .txt 文件中应检测的行的示例:

[05:35:26] [Client thread/INFO]: [CHAT] §6§lP§e§lrof

这是我使用的代码:

    :search
    del C:\Users\Diogo\Desktop\Detector\latest.txt
    del C:\Users\Diogo\Desktop\Detector\latest.log
    xcopy /s "C:\LocationofFile\latest.log" "C:\Users\Diogo\Desktop\Detector"
    RENAME "C:\Users\Diogo\Desktop\Detector\latest.log" "latest.txt"
    @echo off & setlocal enabledelayedexpansion
    for /f "tokens=*" %%c in (C:\Users\Diogo\Desktop\Detector\latest.txt) do (
    set temp=%%c
    )
    echo !temp!
    (echo !temp! | findstr /i /c:"§6§lP§e§lrof" >nul) && (GOTO found) || (echo Variable does not have the string "§6§lP§e§lrof")
    Endlocal
    GOTO search

    :found
    pause

For some reason it doesn't detect it.
Any ideas?

Thank you in advance :D

编辑: 尝试过 Powershell,现在是代码(是的,我正在搜索 2 种不同的东西):

  while ($True) {
Write-Output 'Enter <ctrl><c> to break out of this loop.'
Start-Sleep -Seconds 1
Copy-Item -LiteralPath "C:\LocationOfFile\latest.log" -Destination "C:\Users\Diogo\Desktop\Detector"
Rename-Item -Path "C:\Users\Diogo\Desktop\Detector\latest.log" -NewName "latest.txt"
Get-Content -Path "latest.txt" -tail 1 -wait | Select-String -Quiet '§6§lP§e§lrof'
if (System.Boolean -eq True) {
Invoke-Item result1.bat
pause
}
else {
Get-Content -Path "latest.txt" -tail 1 -wait | Select-String -Quiet 'spawned'
if (System.Boolean -eq True) {
Invoke-Item result2.bat
pause
}
else {
Nope
pause
}
}
}

您的批次的问题是搜索字符串中的“§”字符。 FindStr 仅在搜索字符串仅包含 ASCII 字符时才能正常工作,而“§”不是。

引自

Searching Unicode files

FINDSTR cannot properly search most Unicode (UTF-16, UTF-16LE, UTF-16BE, UTF-32) because it cannot search for nul bytes and Unicode typically contains many nul bytes.

However, the TYPE command converts UTF-16LE with BOM to a single byte character set, so a command like the following will work with UTF-16LE with BOM.

type unicode.txt|findstr "search" Note that Unicode code points that are not supported by your active code page will be converted to ? characters.

It is possible to search UTF-8 as long as your search string contains only ASCII. However, the console output of any multi-byte UTF-8 characters will not be correct. But if you redirect the output to a file, then the result will be correctly encoded UTF-8. Note that if the UTF-8 file contains a BOM, then the BOM will be considered as part of the first line, which could throw off a search that matches the beginning of a line.

It is possible to search multi-byte UTF-8 characters if you put your search string in a UTF-8 encoded search file (without BOM), and use the /G option.

所以基本上你有两个选择: