在文件中搜索字符串并使用autoit在文件中打印第5行

时间:2013-08-07 05:15:52

标签: autoit

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

#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

1 个答案:

答案 0 :(得分: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 +行的文件,你要找的行是在那个文件的最后四分之一但是肯定是个好主意防止可能的性能问题。