2013-08-07 89 views
0

我有一个文本文件包含近20行要搜索文件中的字符串,然后在文件中使用autoit打印下一行第5行,任何人都可以帮助我解决这个问题在文件中搜索字符串,然后打印文件中的第5行使用autoit

#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 

回答

3

,直到搜索串中发现这种读取文本文件,然后在接下来的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 +线和你正在寻找的线路都在该文件的最后一个季度,但它肯定是一个好主意,以防止可能的性能问题。

+0

其工作感谢:) – passionTime

+1

使用'FileReadLine'及其第二个参数在上面的'For ... Next'循环中增加一个参数并不是一个好主意。你不会注意到这样一个小剧本的表现,但只是要记住一些。 – Matt

+0

@Matt:是的,你有一个点。我将编辑我的答案并添加一个不同的解决方案。 – mrt

相关问题