0

ファイル内の文字列を検索し、autoit を使用してファイル内の次の 5 行目を出力する 20 行近くを含むテキスト ファイルがあります。

#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」パラメーターを使用しないループの 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 つのバージョンのスクリプトの間に大きな違いはありませんが、可能なパフォーマンスを防ぐことは確かに良い考えです。問題。

于 2013-08-07T11:58:58.557 に答える