,直到搜索串中发现这种读取文本文件,然后在接下来的5行写到标准输出:
#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-07 11:58:58
mrt
其工作感谢:) – passionTime
使用'FileReadLine'及其第二个参数在上面的'For ... Next'循环中增加一个参数并不是一个好主意。你不会注意到这样一个小剧本的表现,但只是要记住一些。 – Matt
@Matt:是的,你有一个点。我将编辑我的答案并添加一个不同的解决方案。 – mrt