0

I have a text file contains nearly 20 lines wanted to search a string in file and print next 5th line in file using autoit, any one can help me to solve this

#include <File.au3>
#include <array.au3>


$file = @ScriptDir & "\file.txt"
$search = "str"

If FileExists($file) Then
    $contents = FileRead($file)
    If @error Then
        MsgBox(0, 'File Error', $file & ' could not be read.')
    Else
        For $i = 1 To $count
            If StringInStr($contents, $search) Then        
                MsgBox(0, 'Positive', $file & ' does contain the text "' & $search & '"')
            Else
                MsgBox(0, 'Negative', $file & ' does NOT contain the text "' & $search & '"')
            EndIf
        Next
    EndIf
EndIf
4

1 回答 1

3

这会读取文本文件,直到找到搜索字符串,然后将接下来的 5 行写入 STDOUT:

#include <File.au3>
#include <Array.au3>


Global $file = @ScriptDir & "\file.txt", $search = "str"
Global $iLine = 0, $sLine = ''
Global $hFile = FileOpen($file)
If $hFile = -1 Then 
    MsgBox(0,'ERROR','Unable to open file for reading.')
    Exit 1
EndIf

; find the line that has the search string
While 1
    $iLine += 1
    $sLine = FileReadLine($hFile)
    If @error = -1 Then ExitLoop

    ; $search found in the line, now write the next 5 lines to STDOUT
    If StringInStr($sLine, $search)And Not $iValid  Then    
        For $i = $iLine+1 To $iLine+5
            ConsoleWrite($i & ':' & FileReadLine($hFile, $i) & @CRLF)
        Next
        ExitLoop
    EndIf
WEnd
FileClose($hFile)

编辑

由于 Matt 的论点,这里是循环的第二个版本,它不使用FileReadLine的“line”参数。

#include <File.au3>
#include <Array.au3>


Global $file = @ScriptDir & "\file.txt", $search = "str"
Global $iLine = 0, $sLine = '', $iValid = 0
Global $hFile = FileOpen($file)
If $hFile = -1 Then 
    MsgBox(0,'ERROR','Unable to open file for reading.')
    Exit 1
EndIf

; find the line that has the search string
While 1
    $iLine += 1
    $sLine = FileReadLine($hFile)
    If @error = -1 Then ExitLoop

    ; test the line for the $search string until the flag $iValid is set
    If StringInStr($sLine, $search) And Not $iValid Then
        $iValid = 1
        ContinueLoop
    EndIf

    If $iValid Then
        $iValid += 1
        ConsoleWrite($iLine & ':' & $sLine & @CRLF)
        If $iValid > 5 Then ExitLoop
    EndIf
WEnd
FileClose($hFile)

您不会注意到这两个版本的脚本之间有太大区别,除非您正在读取一个包含 10k+ 行的文件,并且您要查找的行位于该文件的最后一个季度,但防止可能的性能肯定是一个好主意问题。

于 2013-08-07T11:58:58.557 回答