在日志文件中查找字符串并在第一个字符串后搜索另一个字符串

时间:2016-06-09 09:44:50

标签: string autoit

我有一个唯一的ID放在一个日志文件中,我可以搜索文件并找到它,一旦我在文件中找到唯一的ID我需要找到另一个字符串(命名为字符串2)后这个唯一的ID并复制字符串2的下一行。

请在下面找到我的功能,并建议如何实现这一目标。

Func getAuthResponse($LogfilePath, $AuthRespFilePath, $UniqueId, $search)

Global $iLine = 0, $sLine = ''
Global $hFile = FileOpen($LogfilePath)

If $hFile = -1 Then
MsgBox(0,'ERROR','Unable to open file for reading.')
Exit 1
EndIf    ;If $hFile = -1 Then

; find the line that has the search string
While 1
$iLine += 1
$sLine = FileReadLine($hFile)

If @error = -1 Then ExitLoop
  ; finding the unique id in the log file

  ;ConsoleWrite($UniqueId & @LF)
  If StringInStr($sLine, $UniqueId) Then
     ConsoleWrite($sLine & @LF)
     ; assuming that unique id is found , now finding the phrase Auth response is as follow : after the unique id
     $sNewLine = $sLine+
     If StringInStr($sLine, $search) Then
        ConsoleWrite($sLine & @LF)

       //// SOME LOGIC ////

     ExitLoop
     EndIf        ;If StringInStr($sLine, $search) Then

  ExitLoop
  EndIf        ;If(StringInStr($sLine, $UniqueId) Then

WEnd        ;While 1
FileClose($hFile)
EndFunc 

2 个答案:

答案 0 :(得分:0)

让我们看看我是否理解正确:

您需要找到一个ID,此ID必须是一个字符串,之后您需要复制下一行。如果这是正确的,我为您制作了一个新的While循环,它现在只是一个For循环。

#include <File.au3>
For $c1 = 1 To _FileCountLines($hFile) Step +1
    $sLine = FileReadLine($hFile, $c1)
    If (StringInStr($sLine, $UniqueId) > 0) Then
        For $c2 = $c1 To _FileCountLines($hFile) Step +1
            $sLine = FileReadLine($hFile, $c2)
            If (StringInStr($sLine, $search) > 0) Then
                $LINE_AFTER_STRING_2 = FileReadLine($hFile, $c2 + 1)
                ExitLoop
            EndIf
        Next
    EndIf
Next

If $LINE_AFTER_STRING_2 = "" Then MsgBox(0, "NOT FOUND", "NOT FOUND")

发生以下事情:首先它循环遍历所有行并搜索您的ID,如果找到它,它会启动一个新的For循环并在ID之后搜索您的字符串,如果它发现它对+1计数+1排队并读取它。这应该是您正在寻找的线。该变量名为$LINE_AFTER_STRING_2,可随意更改。

请勿忘记包含File.au3,因为我使用了_FileCountLines

答案 1 :(得分:0)

试试这个:

#include <File.au3>

Func getAuthResponse($LogfilePath, $UniqueId, $search)

    Local $arrayFile = ""
    Local $output    = ""

    If Not FileExists($LogfilePath) Then Return SetError(1, 0, -1)

    _FileReadToArray($LogfilePath, $arrayFile)

    For $i = 1 To $arrayFile[0]
        If StringInStr($arrayFile[$i], $UniqueId) Then
            For $j = $i+1 To $arrayFile[0]
                If StringInStr($arrayFile[$j], $search) Then
                    $output = $arrayFile[$j+1]
                    ExitLoop
                EndIf
            Next
            ExitLoop
        EndIf       
    Next

    Return $output

EndFunc
相关问题