これは、検索文字列が見つかるまでテキスト ファイルを読み取り、次の 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」パラメーターを使用しないループの 2 番目のバージョンがここにあります。
#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)
10,000 行以上のファイルを読み込んでいて、探している行がそのファイルの最後の 4 分の 1 にある場合を除き、これら 2 つのバージョンのスクリプトの間に大きな違いはありませんが、可能なパフォーマンスを防ぐことは確かに良い考えです。問題。